0

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?

AspiringMat
  • 2,161
  • 2
  • 21
  • 33

1 Answers1

1

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)
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • I actually need the meshgrids since I need to plot it after in matplotlib – AspiringMat Sep 10 '18 at 09:32
  • Hello @Divakar, did you take a look at this [question](https://stackoverflow.com/questions/52242832/remainder-function-runtime-on-numpy-arrays-is-far-longer-than-when-taken-apa)? Your experience could be very valuable. – Eric Duminil Sep 11 '18 at 13:57