Home > OS >  Why does meshgrid have one more dimension than input?
Why does meshgrid have one more dimension than input?

Time:10-08

I am sorry if this is obvious, but I am having trouble understanding why it seems that np.meshgrid produces array who's shape is more than the input:

grid = np.meshgrid(
    np.linspace(-1, 1, 5),
    np.linspace(-1, 1, 4),
    np.linspace(-1, 1, 3), indexing='ij')

np.shape(grid)

(3, 5, 4, 3)

To me it should have been: (5, 4, 3)

or

grid = np.meshgrid(
    np.linspace(-1, 1, 5),
    np.linspace(-1, 1, 4), indexing='ij')

np.shape(grid)

(2, 5, 4)

To me it should have been: (5, 4)

I would be very grateful if somebody could explain me that.... Thanks a lot!

CodePudding user response:

In [92]: grid = np.meshgrid(
    ...:     np.linspace(-1, 1, 5),
    ...:     np.linspace(-1, 1, 4), indexing='ij')
    ...: 
In [93]: grid
Out[93]: 
[array([[-1. , -1. , -1. , -1. ],
        [-0.5, -0.5, -0.5, -0.5],
        [ 0. ,  0. ,  0. ,  0. ],
        [ 0.5,  0.5,  0.5,  0.5],
        [ 1. ,  1. ,  1. ,  1. ]]),
 array([[-1.        , -0.33333333,  0.33333333,  1.        ],
        [-1.        , -0.33333333,  0.33333333,  1.        ],
        [-1.        , -0.33333333,  0.33333333,  1.        ],
        [-1.        , -0.33333333,  0.33333333,  1.        ],
        [-1.        , -0.33333333,  0.33333333,  1.        ]])]

grid is a list with two arrays. The first array has numbers from the first argument (the one with 5 elements). The second has numbers from the second argument.

Why should np.shape(grid) is (5,4)? What layout were you expecting?

np.shape(grid) actually does np.array(grid).shape, which is why there's an added dimension.

  • Related