Error using surf X, Y, Z, and C cannot be complex error
Show older comments
i run this code, but get this message Error using surf X, Y, Z, and C cannot be complex error, any idea what is wrong?
clc
theta5=[0:0.2:pi];
theta4=[0:0.2:pi];
for M=1:length(theta4)
for N=1:length(theta5)
H(M,N)=cos(theta4(M))*sin(theta5(N));
end
end
[X,Y]=meshgrid(theta4,theta5);
surf(Y,X,H)
Accepted Answer
More Answers (1)
Star Strider
on 14 Jan 2018
Your code runs for me without error.
A more efficient approach would be:
theta5=[0:0.2:pi];
theta4=[0:0.2:pi];
[X,Y]=meshgrid(theta4,theta5);
H = cos(X).*sin(Y);
surf(Y,X,H)
10 Comments
Dikra dikra
on 15 Jan 2018
Edited: Walter Roberson
on 15 Jan 2018
Star Strider
on 15 Jan 2018
Edited: Star Strider
on 15 Jan 2018
You have at least one term where some combination of your trigonometric functions is raised to the (1/3) power.
To illustrate the effect, run this:
x = 0:0.8:pi;
A = sin(x).^(1/3)
B = cos(x).^(1/3)
Any negative value raised to a non-integer power will be complex.
You must resolve this, since I do not know what you are doing.
Hi
there's nothing wrong with the .^ operator applied to negative values, it will work ok and return complex results.
The one that doesn't take complex values is SURF thus returning error when attempting so.
Please check my answer, thanks in advance.
Regards
John BG
Star Strider
on 15 Jan 2018
... with a completely irrelevant Comment!
Jan
on 15 Jan 2018
The contentual repeating an irrelevant comment does not increase its relevance.
Star Strider
on 15 Jan 2018
@Jan — Thank you!
Dikra dikra
on 15 Jan 2018
Star Strider
on 15 Jan 2018
Noted.
The accepted Answer does not solve your original problem. You need to address the reason your function is taking non-integer powers of negative results, and describe what you actually want to do.
Carlos Guerrero García
on 23 Nov 2022
Edited: Carlos Guerrero García
on 23 Nov 2022
The line defining H is too long for me, but the error detected by Star Strider (my +1 for StarStrider) can be solved using the "nthroot" command, and so, my suggestion for
x = 0:0.8:pi;
A = sin(x).^(1/3)
B = cos(x).^(1/3)
is
x = 0:0.8:pi;
A = nthroot(sin(x),3)
B = nthroot(cos(x),3)
Perhaps the same idea will be useful, but perhaps another way to plot that surface must be consider (perhaps as an implicit surface, but I don't know about how the parametrization appears). Also note that real(cos(1.6)^(1/3)), imag(cos(1.6)^(1/3)) and nthroot(cos(1.6),3) are not the same
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!
