Search code examples
pythonnumpyarray-broadcasting

Numpy: Find minimum of an expression over several parameters


Is there a numpy way to get the minimum of an expression over many parameters without explicit loops?

#Randomly initialize samples
SAMPLES_NUM = 200
L = np.random.rand(SAMPLES_NUM)
q1 = np.random.rand(SAMPLES_NUM)
q2 = np.random.rand(SAMPLES_NUM)

#Make the data
X = np.arange(0,1,0.01)
Y = np.arange(0,1,0.01)
X,Y = np.meshgrid(X,Y)

#Calculate Z at (x,y) as the minimum of L[i]+x(q1[i]+q2[i]) + q2[i]y
#over all  i

I tried broadcasting:

Z = np.min(L + X*(q1+q2) +Y*q2)

But doesn't work because of broadcasting issues. Any ideas, or would I have to explicitly loop over all i?


Solution

  • Using the meshgrid versions, we could extend dims of X, Y and that brings in broadcasting, when those operations are performed with other inputs and finally using min along the last axis -

    np.min(L + X[...,None]*(q1+q2) + Y[...,None]*q2,axis=2)