MATLAB: Using trigonometric function in Matlab

magnetic fieldquiver3

Hi, I am trying to model a dipole magnetic field using the quiver3 function. However when I use a trigonometric function in one of my arrow direction vectors i get the error:
Error using * Inputs must be 2-D, or at least one input must be scalar. To compute elementwise TIMES, use TIMES (.*) instead.
Here is the code i'm using
if true
[X,Y,Z] = meshgrid(-10:.5:10, -10:.5:10, -10:.5:10); %defines meshgrid coverage
r=(X.^2+Y.^2+Z.^2).^0.5 ;
k=50;
T=Z./r;
U=3*k*Z.*sin(acos(T))*r.^-4;
V=3*k*Z.*sin(acos(T))*r.^-4;
W=2*k*((3*Z.^2 * r.^-2)-1)*r.^-3;
%magnetic field function
figure
quiver3(X,Y,Z,U,V,W,0.5)% no defines arrow length, other define direction
%defines arrow direction (u,v,w) at point (x,y,z)
hold on
%surf(X,Y,Z) %produces surface
axis equal %defines axis parameters
hold off
% code
end
Does anyone have any idea how i can rectify this? Thanks in advance, John

Best Answer

When in doubt, vectorise everything:
U=3*k*Z.*sin(acos(T))./r.^4;
V=3*k*Z.*sin(acos(T))./r.^4;
W=2*k*((3*Z.^2 ./ r.^2)-1)./r.^3;
This produces your plot, but you may want to tweak the arrow lengths in order to see them.