Meshgrid function different order
22 views (last 30 days)
Show older comments
Rafael Luque
on 5 Aug 2019
Commented: Steven Lord
on 5 Aug 2019
I have this code:
x = 0:1:5;
y = 0:1:5;
z = 0:1:5;
meshgrid(x, y, z);
[x_a, y_a, z_a] = meshgrid(x, y, z);
Mesh = [x_a(:), y_a(:), z_a(:)];
Mesh =
0 0 0
0 1 0
... ... ...
0 5 0
1 0 0
1 1 0
... ... ...
1 5 0
2 0 0
2 1 0
... ... ...
0 0 1
0 1 1
... ... ...
But I wish Mesh was:
0 0 0
0 0 1
... ... ...
0 0 5
0 1 0
0 1 1
... ... ...
0 1 5
0 2 0
0 2 1
... ... ...
5 5 0
5 5 1
... ... ...
It seems that, with meshgrid function, x and y change first while z is constant, but what I mean is the opposite, x and y are constant first and z change. Is it possible with meshgrid function?
0 Comments
Accepted Answer
Neuropragmatist
on 5 Aug 2019
x = 0:1:5;
y = 0:1:5;
z = 0:1:5;
[y_a, z_a, x_a] = meshgrid(y,z,x);
Mesh = [x_a(:),y_a(:),z_a(:)]
Or probably better:
x = 0:1:5;
y = 0:1:5;
z = 0:1:5;
[x_a,y_a,z_a] = meshgrid(x,y,z);
Mesh = sortrows(sortrows([x_a(:),y_a(:),z_a(:)],2),1)
Hope this helps,
M.
3 Comments
Neuropragmatist
on 5 Aug 2019
Yea, you are right. I played around with this and didn't get the results I expected so I settled on wrapping it. Do you know why the order of the columns is reversed between the two?
More Answers (1)
Guillaume
on 5 Aug 2019
Personally, I think meshgrid is an abomination as it doesn't really makes its mind what order the dimensions are in. It iterates over the dimensions in the order [2, 1, 3] (and doesn't do more than 3).
ndgrid on the other hand iterates in a logical order, [1, 2, 3, ...] and works for as many dimensions as you want (or your computer can manage).
So, I'd recommend using ndgrid. With either, you can of course swap the order of the input to get them to iterate in the order you want.
2 Comments
Steven Lord
on 5 Aug 2019
meshgrid predates ndgrid, which I believe was only introduced when N-dimensional (N > 2) arrays were introduced to MATLAB in MATLAB 5.0 (December 1996 according to Wikipedia.)
I believe meshgrid was introduced in MATLAB 4.0 (1994) but there appears to be an older function named meshdom that looks very similar in MATLAB 3.5 (1990). I haven't gone any further back than that.
Of course, all those dates predate the start of my tenure at MathWorks by at least a couple years.
See Also
Categories
Find more on Surface and Mesh Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!