Search code examples
matlabcoordinatescalculuspolar-coordinates

Graphing something on matlab


So im trying to draw on Matlab and this is what I have so far from my source code:

phi=linspace(0,pi,100);
theta=linspace(0,pi,100);
r=phi.^2+theta.^2;

x=r.*sin(phi).*cos(theta);
y=r.*sin(phi).*sin(theta);
z=r.*cos(phi);
plot3(x,y,z,'*')

However this only gives me one slice, I want multiple slices. How do I go about doing this? Thank you!


Solution

  • There are several problems with your code:

    • In your code as it stands, theta and phi are vectors. Each value of phi is associated with a value of theta. That gives a line, not a surface. To generate a surface you need to generate a grid with all the combinations of theta, phi values in the form of matrices. This can be done with ndgrid.
    • The equations for the torus seem to be wrong. I'm taking them from the Wikipedia.
    • theta, phi should vary from 0 to 2*pi (not from 0 to pi).

    Code:

    phi = linspace(0,2*pi,100);
    theta = linspace(0,2*pi,100);
    [pp, tt] = ndgrid(phi,theta);
    R = 1;
    r = 1;
    x = (R+r.*cos(tt)).*cos(pp);
    y = (R+r.*cos(tt)).*sin(pp);;
    z = r.*sin(tt);
    plot3(x,y,z,'*')
    

    Figure:

    enter image description here