3d meshgrid returning values with x and y components flipped

I created a 3d vector field using meshgrid. The field looks great when plotting with both quiver3 and stream3. The issue arrises when I attempt to pull the vector components from a specific index(position)
Here is the code:
L = 100;
k = pi/L;
x0 = 51;
y0 = 51;
z0 = 51;
[x, y, z] = meshgrid(x0-L/2:x0+L/2, y0-L/2:y0+L/2, z0-L/2:z0+L/2);
Bx = -(5./8).*k.*(x-x0).*sin(k*(z-z0));
By = -(5./8).*k.*(y-y0).*sin(k*(z-z0));
Bz = 5*(1 - 1/2 * (1 + k^(2)/8 * ((x-x0).^2 + (y-y0).^2)) .* cos(k.*(z-z0)));
xi = 55; yi= 65; zi=75;
Bi = [Bx(xi,yi,zi), By(xi,yi,zi), Bz(xi,yi,zi)]
Bi should return:
[-0.0538 -0.1882 3.1299] (exact solution)
But instead returns:
[-0.1882 -0.0538 3.1299] with the x and y components flipped.
Any suggestions?

 Accepted Answer

This is the difference between meshgrid and ndgrid.
[A, B] = meshgrid(1:2, 3:4)
A = 2×2
1 2 1 2
B = 2×2
3 3 4 4
[A, B] = ndgrid(1:2, 3:4)
A = 2×2
1 1 2 2
B = 2×2
3 4 3 4

1 Comment

xi = 55; yi= 65; zi=75;
Bi = [Bx(xi,yi,zi), By(xi,yi,zi), Bz(xi,yi,zi)]
x is the second index of an array, not the first index.
The first index in MATLAB is the row number, the second is the column number. Rows correspond to vertical height, columns correspond to horizontal distance. By convention, cartesian x corresponds to horizontal distance and cartesian y corresponds to vertical distance. Match on vertical / horizontal and you see that x is the second coordinate and y is the first coordinate.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!