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
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 tomeshgrid
, howeverndgrid
supports 1-D to N-D whilemeshgrid
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 vectorsx1gv, x2gv
andx3gv
of lengthM
,N
andP
respectively,ndgrid(x1gv, x2gv)
will output arrays of sizeM
-by-N
whilemeshgrid(x1gv, x2gv)
outputs arrays of sizeN
-by-M
. Similarly,ndgrid(x1gv, x2gv, x3gv)
will output arrays of sizeM
-by-N
-by-P
whilemeshgrid(x1gv, x2gv, x3gv)
outputs arrays of sizeN
-by-M
-by-P
.