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

2 views (last 30 days)
i run below code, but get X, Y, Z, and C cannot be complex error, any idea what is wrong?
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

Answers (1)

Thomas Koelen
Thomas Koelen on 3 Apr 2015
Edited: Thomas Koelen on 3 Apr 2015
you were taking square roots of negative values, thus giving complex values.
r=abs(sqrt((4*V.^-k)./(cos(U).^2+k*sin(U).^2)));
should work

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!