Meshgrid-like function to generate 4D arrays in Matlab

后端 未结 1 1531
死守一世寂寞
死守一世寂寞 2021-01-21 16:07

I have a 4 dimension mathematical function I want to implement in matlab, but the meshgrid function works for at most 3 dimensions. Is there a similar function for

1条回答
  •  独厮守ぢ
    2021-01-21 16:29

    Yes, use ndgrid. ndgrid extends for dimensions beyond 3, but you can most certainly use it for 2 or 3. meshgrid is a special case of ndgrid.

    However, one caveat I would like to mention is that the way the X and Y coordinates are arranged between meshgrid and ndgrid are interchanged. Specifically, X traverses horizontally in meshgrid while X traverses vertically in ndgrid. Similarly Y traverses vertically in meshgrid while Y traverses horizontally in ndgrid.

    Therefore, to get the same behaviour for 2 or 3 dimensions, do:

    [X,Y] = meshgrid(...)
    [Y,X] = ndgrid(...)
    

    Or:

    [X,Y,Z] = meshgrid(...)
    [Y,X,Z] = ndgrid(...)
    

    Using ndgrid for higher dimensions maintains that same order with regards to the horizontal and vertical coordinates.

    To be more explicit, this is what the note for ndgrid says at the end of the documentation:

    The ndgrid function is similar to meshgrid, however ndgrid supports 1-D to N-D while meshgrid is restricted to 2-D and 3-D. The coordinates output by each function are the same, but the shape of the output arrays in the first two dimensions are different. For grid vectors x1gv, x2gv and x3gv of length M, N and P respectively, ndgrid(x1gv, x2gv) will output arrays of size M-by-N while meshgrid(x1gv, x2gv) outputs arrays of size N-by-M. Similarly, ndgrid(x1gv, x2gv, x3gv) will output arrays of size M-by-N-by-P while meshgrid(x1gv, x2gv, x3gv) outputs arrays of size N-by-M-by-P.

    0 讨论(0)
提交回复
热议问题