I have Python / Numpy code that runs slowly, and I think this is due to using a double for loop. Here is the code.
def heat(D,u0,q,tdim): xdim = np.size(u0) Z = np.zeros([xdim,tdim]) Z[:,0]=u0; for i in range(1,tdim): for j in range (1,xdim-1): Z[j,i]=Z[j,i-1]+D*q*(Z[j-1,i-1]-2*Z[j,i-1]+Z[j+1,i-1]) return Z
I am trying to remove double for a loop and vectorize Z. Here is my attempt.
def heat(D,u0,q,tdim): xdim = np.size(u0) Z = np.zeros([xdim,tdim]) Z[:,0]=u0; Z[1:,1:-1]=Z[1:-1,:-1]+D*q*(Z[:-2,:-1]-2*Z[1:-1,:-1]+Z[2:,:-1]) return Z
This does not work. I get the following error:
operands could not be broadcast together with shapes (24,73) (23,74)
So, somewhere in an attempt to vectorize Z, I messed up. Could you help me identify my mistake?