Search code examples
matlabplotsurf

Matlab, Error using surf, X, Y, Z, and C cannot be complex


i run below code, but get X, Y, Z, and C cannot be complex error, any idea what is wrong?

 k=1;
 u = linspace(0,2*pi,72); 
 v = [-3:.2:-1,1:.2:3];
 [U,V] = meshgrid(u,v);
 r=sqrt((4*V.^-k)./(cos(U).^2+k*sin(U).^2));
 X = r.*cos(U); 
 Y = r.*sin(U);
 Z = V;

This is the image I want to get:

http://adasu.info/plates.png

The full code is:

function simple_math_functions_animation1
clc, close all, clear all

hf1=figure(1);hold on,grid on,axis equal, view([1 -1 1])
set(hf1,'Color','w');set(hf1,'Position',[300, 600, 500, 400]);
xlabel('x');ylabel('y'),zlabel('z');

 k=1;
 u = linspace(0,2*pi,72);
 v = [-3:.2:-1,1:.2:3];
 [U,V] = meshgrid(u,v);
 r=sqrt((4*V.^-k)./(cos(U).^2+k*sin(U).^2));
 X = r.*cos(U);
 Y = r.*sin(U);
 Z = V;

surf(X,Y,Z,'EdgeColor',[0.5 1. 0.2],'FaceColor',[1 0.2 0.8],'FaceAlpha',0.6);

XYZ=[reshape(X,1,prod(size(X)));
     reshape(Y,1,prod(size(Y)));
     reshape(Z,1,prod(size(Z)));
     ones(1,prod(size(Z)))];
phi=[0 : pi/20 : 50*pi];
h=[]; axis([-20 20 -20 20 -20 20]);

for beta=phi   % animation loop  *****************

    T=[cos(beta) -sin(beta) 0    0;     % rotation matrix
       sin(beta)  cos(beta) 0    0;
        0          0        1    0;
        0          0        0    1];

    XYZ1=T*XYZ;  % coordinates changing
    X1=reshape(XYZ1(1,:),size(X));Y1=reshape(XYZ1(2,:),size(Y));Z1=reshape(XYZ1(3,:),size(Z));
    pause(0.1);if ~isempty(h),delete(h);end
    h=surf(X1,Y1,Z1,'EdgeColor',[0.5 1. 0.2],'FaceColor',[0.2 0.2 0.8],'FaceAlpha',0.6);

end       % ******************************************

end

Solution

  • You are getting that complex error because r is complex-valued. r is used in both X and Y and so when it's time to use surf on these inputs, you finally get that error. That makes sense because your range of V has negative values, and when you set k=1 for this expression:

    r=sqrt((4*V.^-k)./(cos(U).^2+k*sin(U).^2));
    

    You are effectively trying to take the square root of values in V and some of them are negative, and hence r is complex valued. If you look at your actual image you uploaded, you are missing a 2 in the power of V. Therefore:

    r=sqrt((4*V.^2-k)./(cos(U).^2+k*sin(U).^2));
    

    When I do this, then try running your code, I get this:

    enter image description here