MATLAB: 3d meshgrid returning values with x and y components flipped

meshgridvector

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?

Best 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
Related Question