Search code examples
matlabplotsystemcoordinate

Plotting spherical coordinate system in Matlab


I want to draw a spherical coordinate system in Matlab.

This is the kind of image I'd like to create:

This is what I'd like to create in matlab.

Could someone give me some hints? (So far I've plotted the cartesian coordinates)

Here is what I have tried myself:

hold on
x0=0;
y0=0;
z0=0;

plot3(x0+[0, 1, nan, 0, 0, nan, 0, 0], y0+[0, 0, nan, 0, 1, nan, 0, 0], z0+[0, 0, nan, 0, 0, nan, 0, 1] )       
text([x0+1, x0, x0], [y0, y0+1, y0], [z0, z0, z0+1], ['X';'Y';'Z']);

r=0.5;
[x,y,z] = sphere(100); 
hsurf = surf(x*r, y*r, z*r);
axis equal;

Solution

  • function[]=SphereToCartesian(r,theta,phi)
    %% plot cartesian coordinates:
    plot3([0 0 0;r 0 0],[0 0 0;0 r 0],[0 0 0;0 0 r],'k');
    
    %% plot the ball
    line('xdata',sphcart(r,theta,phi,'x'),'ydata',sphcart(r,theta,phi,'y'),'zdata',sphcart(r,theta,phi,'z'),'marker','.','markersize',5);
    
    %% Plot the arm
    line('xdata',[0 sphcart(r,theta,phi,'x')],'ydata',[0 sphcart(r,theta,phi,'y')],'zdata',[0 sphcart(r,theta,phi,'z')],'linestyle','--');
    
    %% Plot the projections
    line('xdata',[0 sphcart(r,theta,phi,'x')],'ydata',[0 sphcart(r,theta,phi,'y')],'zdata',[0 0],'linestyle','--');
    
    %% Plot the arcs
    thetas=[0:0.1:theta theta];
    line('xdata',sphcart(.1*r,thetas,phi,'x'),'ydata', sphcart(.1*r,thetas,phi,'y'),'zdata',sphcart(.1*r,thetas,phi,'z'));
    
    %% Labels
    text(sphcart(r,theta,phi,'x'),sphcart(r,theta,phi,'y'),sphcart(r,theta,phi,'z'),'r (x,y,z)')
    
    %% transform
     function[OUT]=sphcart(R,THETA,PHI,COORD)
      if strcmpi(COORD,'x')
       OUT=R.*cos(THETA).*cos(PHI);
      elseif strcmpi(COORD,'y')
       OUT=R.*cos(THETA).*sin(PHI);
      elseif strcmpi(COORD,'z')
       OUT=R.*sin(THETA)
      else
       disp('Wrong coordinate!');
       OUT=nan;
      end
     end
    end
    

    The rest you can do using axes and figure properties.