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!

1 Answer 1

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))

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, avoid meshgrid when possible! +1 I recently went on a rant about this same thing. So much confusion seems to arise from meshgrid.
@chappjc Your rant is well justified I think :-) My favourite one is 'versus .'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.