I am trying to vectorize my code. Am I converting
def acceleration_1(grid):
nx = grid.shape[0]
ny = grid.shape[1]
acc = np.zeros((nx,ny,2))
for i in range(1,nx-1):
for j in range(1,ny-1):
acc[i,j,0] = grid[i+1,j,0] + grid[i-1,j,0] - 2*grid[i,j,0]
acc[i,j,1] = grid[i,j+1,1] + grid[i,j-1,1] - 2*grid[i,j,1]
to this
def acceleration_2(grid):
nx = np.arange(1,grid.shape[0]-1)
ny = np.arange(1,grid.shape[1]-1)
acc = np.zeros((grid.shape[0],grid.shape[0],2))
acc[nx,ny,0] = grid[nx+1,ny,0] + grid[nx-1,ny,0] - 2*grid[nx,ny,0]
acc[nx,ny,1] = grid[nx,ny+1,1] + grid[nx,ny-1,1] - 2*grid[nx,ny,1]
properly?
I know I could represent this as matrix multiplication as well. But it just seems cumbersome to have to convert it to matrix operations. Do I get the best speedup by converting the for loops to an implicit iteration over "nx" and "ny"?
[i,j,0]and[i,j,1]? Your array shape is only 2D, as well.grid[i,j+1,1]begrid[i,j+1,2]?