I would like to apply a (more complex?) function on my 3d numpy array with the shape x,y,z = (4,4,3). Let's assume I have the following array:
array = np.arange(48)
array = array.reshape([4,4,3])
Now I would like to call the following function on each point of the array:
p(x,y,z) = a(z) + b(z)*ps(x,y)
Let's assume a and b are the following 1d arrays, respectively ps a 2d array.
a = np.random.randint(1,10, size=3)
b = np.random.randint(1,10, size=3)
ps = np.arrange(16)
ps = ps.reshape([4,4])
My intuitive approach was to loop over my array and call the function on each point. It works, but of course it's way too slow:
def calcP(a,b,ps,x,y,z):
p = a[z]+b[z]*ps[x,y]
return p
def stupidLoop(array, a, b, ps, x, y, z):
dummy = array
for z in range (0, 3):
for x in range (0, 4):
for y in range (0, 4):
dummy[x,y,z]=calcP(a,b,ps,x,y,z)
return dummy
updatedArray=stupidLoop(array,a, b, ps, x, y, z)
Is there a faster way? I know it works with vectorized functions, but I cannot figure it out with mine.
I didn't actually try it with these numbers. It's just to exemplify my problem. It comes from the Meteorology world and is a little more complex.
ps = ps.reshape([4,4])? There is some error with the ndarrays you've shareddummy = a[:, np.newaxis, np.newaxis] + b[:, np.newaxis, np.newaxis] * ps(according to the snippet, because in the formula you wrote first the indices are in different order, so it would bea + b * p[:, :, np.newaxis]).updatedArrayshould have the exact same dimensions as my old variablearray. And why should I add more dimensions to a, b and ps withnp.newaxis?mapfunction will only iterate over the outer dimension of a numpy array. It does not understand the inner dimensions.