I am trying to improve numpy performance by applying operations on a 2d array, the problem is that the value at each element in the array depends on the i,j location of that element.
Obviously the easy way to do this is to use a nested for-loop, but I was wondering if there might be a better way by referencing np.indices or something along those lines? Here is my ‘stupid’ code:
for J in range(1025):
for I in range(1025):
PSI[I][J] = A*math.sin((float(I+1)-.5)*DI)*math.sin((float(J+1)-.5)*DJ)
P[I][J] = PCF*(math.cos(2.*float(I)*DI)+math.cos(2.*float(J)*DJ))+50000.
Since you’re doing multiplication among your two arrays, you can use the outer function, after using
arangeto get arrays of your sin/cos.Something like this (use numpy’s trig functions, since they’re vectorized)
If your environment is set up using
from numpy import *orfrom pylab import *, then you don’t need thosenumpy.prefixes before your trig functions. I kept them in to distinguish them from themathones, which won’t work for this approach.