Home > database >  how to vectorize nested for loops in numpy
how to vectorize nested for loops in numpy

Time:11-14

I have been trying to solve this question but I was stuck in limbo

v,u,j=file.shape
for v in range(height):
  for u in range(width):
    start[v,u,0] = -0.5   u / (width-1)
    start[v,u,1] = (-0.5   v / (height-1)) * height / width
    start[v,u,2] = 0

after I used this function I couldn't go further

   v,u,j=file.shape
   x,y,z=np.mgrid(0:v,0:u,0:j)

I hope you help me with a detailed solution to understand well the mechanism thanks in advance

CodePudding user response:

You should always provide a minimal working example. Otherwise we can only guess.

I've converted your code into this working example. It may or may not reflect what you are really trying to do:

file = np.random.random((300, 200, 3))

start = np.empty_like(file)
height, width, _ = file.shape
for v in range(height):
    for u in range(width):
        start[v, u, 0] = -0.5   u / (width - 1)
        start[v, u, 1] = (-0.5   v / (height - 1)) * height / width
        start[v, u, 2] = 0

The following code produces the same result. Notice how an individual value is replaced by a vector in each of your expressions:

start_bis = np.zeros_like(file)
u = -0.5   np.arange(width) / (width - 1)
v = (-0.5   np.arange(height) / (height - 1)) * height / width
start_bis[..., 0], start_bis[..., 1] = np.meshgrid(u, v)
  • Related