henry
henry

Reputation: 975

Why does meshgrid have one more dimension than input?

I am having trouble understanding why it seems that np.meshgrid produces array whose 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). Why is it not?

Upvotes: 0

Views: 112

Answers (1)

hpaulj
hpaulj

Reputation: 231738

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.

Upvotes: 1

Related Questions