1

I often have a function that returns a single value such as a maximum or integral. I then would like to iterate over another parameter. Here is a trivial example using a parabolic. I don't think its broadcasting since I only want the 1D array. In this case its maximums. A real world example is the maximum power point of a solar cell as a function of light intensity but the principle is the same as this example.

import numpy as np
x = np.linspace(-1,1) # sometimes this is read from file
parameters = np.array([1,12,3,5,6]) 
maximums = np.zeros_like(parameters)

for idx, parameter in enumerate(parameters):
    y = -x**2 + parameter
    maximums[idx] = np.max(y) # after I have the maximum I don't need the rest of the data.

print(maximums)

What is the best way to do this in Python/Numpy? I know one simplification is to make the function a def and then use np.vectorize but my understanding is it doesn't make the code any faster.

1

1 Answer 1

1

Extend one of those arrays to 2D and then let broadcasting do those outer additions in a vectorized way -

maximums = (-x**2 + parameters[:,None]).max(1).astype(parameters.dtype)

Alternatively, with the explicit use of the outer addition method -

np.add.outer(parameters, -x**2).max(1).astype(parameters.dtype)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.