MATLAB Answers

# meshgrid provides wrong dimensions

42 views (last 30 days)
Nathaniel Werner on 21 Jun 2017
Edited: Stephen Cobeldick on 22 Jun 2017
Hello,
I am using the meshgrid function to try and make a grid for my surface plots. My x,y, and z arrays are length 102, 42, and 102 respectively. But when I run [X,Y,Z] = meshgrid(x,y,z) the output has the wrong dimensions. X, Y and Z are 42 x 102 x 102 not 102 x 42 x 102. Can someone help me understand what is going wrong with this?
I tried playing around with the order and if I have [X,Y,Z] = meshgrid(y,x,z) it gives the correct output size of 102 x 42 x 102. For now I can run the code using this alternative order but I would like to know why it is making the wrong size.
Thanks
##### 1 CommentShowHide None
Stephen Cobeldick on 22 Jun 2017
That is the correct behavior of meshgrid. You should be using ndgrid instead.
(And learn to navigate to the bottom of the help page, where you will find a list of "See Also" functions. You would have found ndgrid yourself quite simply by scrolling to the bottom of the page)

Sign in to comment.

### Accepted Answer

Jan on 21 Jun 2017
Edited: Jan on 21 Jun 2017
Why do you assume that the output is "wrong"? It is exactly how defined in the documentation:
[X,Y,Z] = meshgrid(x,y,z) returns 3-D grid coordinates defined by the
vectors x, y, and z. The grid represented by X, Y, and Z has size
length(y)-by-length(x)-by-length(z).
Well, length(y)-by-length(x)-by-length(z) sounds strange, I agree. But the function works as advertised. Note: Never trust your expectations, what a function returns, but trust only the documentation. Intuition is fine, but programming languages have been designed by human. ;-)
A similar problem is gradient:
[FX,FY] = gradient(F)
Now FX is along the "horizontal direction", FY the "vertical direction". Sounds okay. But in
[FX,FY,FZ] = gradient(F)
the 1st output concerns the 2nd dimension, the 2nd output the 1st one and the 3rd output the 3rd one. Brrr.
##### 1 CommentShowHide None
Steven Lord on 21 Jun 2017
Consider using ndgrid for this type of operation instead. See the Tips section on that page.

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!