why complex value appears in this array

2 次查看(过去 30 天)
Hi guys.
I am quite new to matlab and I have been spending all my day to figure out why this simple code wont work. I am sure there are easier ways to solve this problem but what I would like to do is create a point set in x,y coordinates. Anyways up to 4th condition code works, when it goes to 4th condition (when idx is 46) y values becomes complex and there is no reason. yyy temp calculation should be equal to y(46). Any ideas? Thanks in advance.
%create point set in cartesian plane(xi,yi)
r1 = 20;
r2 = 12;
rt = 2*(r1+r2);
length = 3*r1+2*r2;
x1 = [0:1:length];
idx = 1;
while idx <= 46
if x1(idx)<= r1
y(idx)= sqrt(r1^2-x1(idx)^2);
elseif r1 < x1(idx) <= r1+r2
y(idx)= -1*(sqrt(r2^2-(r2+r1-x1(idx))^2));
elseif r1+r2 < x1(idx) <= r1+2*r2
y(idx)= -1*(sqrt(r2^2-(x1(idx)-r1-r2)^2));
elseif r1+2*r2 < x1(idx) <= 2*r1+2*r2
temp1=r1^2
temp2=rt-x1(idx)
temp3=temp2^2
y(idx)= sqrt(temp1-temp3)
else
temp4=r1^2;
temp5=x1(idx)-rt;
temp6=temp2^2;
y(idx)= sqrt(temp1-temp3);
end
idx = idx+1;
end
x1(46)
y(46)
temp1=r1^2
temp2=rt-x1(46)
temp3=temp2^2
yyy= sqrt(temp1-temp3)

采纳的回答

Guillaume
Guillaume 2016-7-6
A < B < C is not how you check if B is between A and C. The proper way to do this is:
if A < B && B < C
When you write A < B < C, matlab first compare A < B. The result of that is either false (0) or true (1). It then compare that result (0 or 1) to C.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by