Home > Blockchain >  Why does Meshgrid differ from the for loop here for filling in this tensor?
Why does Meshgrid differ from the for loop here for filling in this tensor?

Time:10-11

I'm trying to fill in this 3dimensional tensor efficiently using Meshgrid instead of using for loops, and it seems like the Meshgrid way does not give me what I expect( for loop way).

import numpy as np

def s(x,y,z,w):
    return x   y   z   w   .1*.1


arr_x = [5,6,3,4,3]
arr_y = [5,3,3,10,34]
T_1 = [5,6,10]
nx = len(arr_x)
ny = len(arr_y)

zx, zy, zt = np.meshgrid(arr_x, arr_y, T_1, sparse = True)
Z = s(zx, zy, zt, 0)
print(Z[4])

for i in range(nx):
    for j in range(ny):
        for k in range(3):
            Z[i,j,k] = s(arr_x[i],arr_y[j],T_1[k],0)
print("----------")
print(Z[4])

Why do I get this as an output, I would think they would be the same?


[[44.01 45.01 49.01]
 [45.01 46.01 50.01]
 [42.01 43.01 47.01]
 [43.01 44.01 48.01]
 [42.01 43.01 47.01]]
----------
[[13.01 14.01 18.01]
 [11.01 12.01 16.01]
 [11.01 12.01 16.01]
 [18.01 19.01 23.01]
[42.01 43.01 47.01]]

CodePudding user response:

Add indexing='ij' to the meshgrid call, and all will be well. It's a difference between matrix indexing and image indexing, where x and y are swapped.

  • Related