1

This should be a really simple question, but for some reason I'm getting unreasonably confused and the Matlab documentation isn't helping.

Given a uniform grid of coordinates (x_i,y_j,z_k), I want to make a 3-dimensional array F in Matlab such that F(i,j,k)=f(x_i,y_j,z_k). The following is obviously incorrect:

x=linspace(-1,1,100)  % uniform mesh on [-1,1]^3
[X,Y,Z]=meshgrid(x);

f=X.*Y.*sin(pi*Y.*Z)   % for example

Do I need to use permute somewhere? I know that I could simply make a triple loop, but as we know that is slow.

Thanks!

icurays1
  • 360
  • 3
  • 13

1 Answers1

4

Use ndgrid instead of meshgrid to avoid the unwanted permutation between first and second dimensions.

From the documentation (see also here):

MESHGRID is like NDGRID except that the order of the first two input and output arguments are switched (i.e., [X,Y,Z] = MESHGRID(x,y,z) produces the same result as [Y,X,Z] = NDGRID(y,x,z))

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 1
    Yes, avoid meshgrid when possible! +1 I recently [went on a rant](http://stackoverflow.com/a/22461766/2778484) about this same thing. So much confusion seems to arise from `meshgrid`. – chappjc Mar 28 '14 at 21:21
  • @chappjc Your rant is well justified I think :-) My favourite one is [`'`versus `.'`](http://stackoverflow.com/questions/22258444/transfer-function-in-time-domain) – Luis Mendo Mar 28 '14 at 23:10