Meshgrid function different order

조회 수: 7 (최근 30일)
Rafael Luque
Rafael Luque 2019년 8월 5일
댓글: Steven Lord 2019년 8월 5일
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?

채택된 답변

Neuropragmatist
Neuropragmatist 2019년 8월 5일
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
Neuropragmatist
Neuropragmatist 2019년 8월 5일
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?
Rafael Luque
Rafael Luque 2019년 8월 5일
Thank you very much!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2019년 8월 5일
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
Adam Danz
Adam Danz 2019년 8월 5일
+1 meshgrid has caused so much confusion.
Steven Lord
Steven Lord 2019년 8월 5일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Surface and Mesh Plots에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by