user26061
user26061

Reputation: 11

iterate over two numpy arrays return 1d array

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.

Upvotes: 1

Views: 155

Answers (1)

Divakar
Divakar

Reputation: 221524

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)

Upvotes: 1

Related Questions