Search code examples
matlabmatlab-figure

Unexpected colors in `surf` plot


I'm trying to write a matlab code that will answer the following question:

Using functions linspace,meshgrid,surf and dot operations, plot the surface of the cones: z=sqrt(x^2+y^2) and z=-sqrt(x^2+y^2). Use the vector form of the coordinate transformation x=rcos(θ),y=rsin(θ), where 0 ≤ θ ≤ 2π and 0 ≤ r ≤ 2. Make the partition composed of 10 values of r and 22 values of θ.

So, my code looks like this:

clear all
clc

theta = linspace(0,2*pi,22); r = linspace(0,2,10);
[R,T] = meshgrid(r,theta);
x = R.*cos(T); y = R.*sin(T);
z = R;
X = [x x]; Y = [y y]; Z = [z -z];
surf(X,Y,Z);

I'm getting the following figure: enter image description here

I don't know how to explain why the upper cone is colored that way.

Is there any way to fix it? Please help, thanks!


Solution

  • You are putting multiple z values for same x,y. In fact, I am surprised it even worked in this way.

    Try plotting the two parts separately:

    clear all
    clc
    
    theta = linspace(0,2*pi,22); r = linspace(0,2,10);
    [R,T] = meshgrid(r,theta);
    x = R.*cos(T); y = R.*sin(T);
    z = R;
    X = [x]; Y = [y]; Z = [z];
    figure();
    surf(X,Y,Z);
    
    hold on;
    surf(X,Y,-Z);
    

    enter image description here