My code is returning complex numbers

133 views (last 30 days)
Jaxom Moore
Jaxom Moore on 14 Mar 2021
Edited: Walter Roberson on 15 Mar 2021
I have the following script:
H=100;
i=250;
for r=1:1:i/2; %don't want to have a circle that is larger than the slope being analyzed.
for x=1:1:2*r;
th(r,x)=acos(x/(r));
ciry(r,x)=(sin(th(r,x))-1)*r+H;
end
end
I'm trying to find the y coordinates for a half-circle at every integer of x, with the center of the circle located at (r,H). However, for whatever reason it is returning complex numbers for all the values of th and ciry. What is weird is that when I run the script below, it doesn't return complex numbers:
H=100;
i=250;
for r=1:1:i/2; %don't want to have a circle that is larger than the slope being analyzed.
for x=1:1:r; %<- this is the difference, no longer 2*r, however, this falls short of what I need, as the program isn't finding the values over the entire diameter of the circle.
th(r,x)=acos(x/(r));
ciry(r,x)=(sin(th(r,x))-1)*r+H;
end
end
If anyone can help I'd greatly appreciate it.

Answers (2)

Cris LaPierre
Cris LaPierre on 14 Mar 2021
Edited: Cris LaPierre on 14 Mar 2021
The issue is that acos is defined between [-1 1]. When you multiply r by 2, you cause your code to take the acos of numbers >1. The acos of any value >1 is imaginary.
For more, see the function description in the documentation.
Y = acos(X) returns the Inverse Cosine (cos-1) of the elements of X in radians. The function accepts both real and complex inputs.
  • For real values of X in the interval [-1, 1], acos(X) returns values in the interval [0, π].
  • For real values of X outside the interval [-1,1] and for complex values of X, acos(X) returns complex values.

John D'Errico
John D'Errico on 14 Mar 2021
Edited: John D'Errico on 14 Mar 2021
What value of x yields cos(x) == 2?
It might be the new math, but I don't recall any common values of x, such that cos(x) is ever as large as 2. In fact, that can only ever happen when you extend the trig functions into the complex plane. So you need to have a complex value for x such that happens.
acos(2)
ans = 0.0000 + 1.3170i
As it turns out, when x is an imaginary number we can get values for cos(x) that exceed 1.
Why is all of this pertinent? Because you are calling acos with arguments that are larger then 1. I dont know why you think your code needs to do that.
That is, pick some value for r. Now x varies from 1 to 2*r. What is 2*r/r? Yep...
r = 1;
x = 2*r;
x/r
ans = 2
acos(x/r)
ans = 0.0000 + 1.3170i
Actually, I might hazard a guess where you went wrong. It looks like you are running the loop on x from 1 to 2r. But perhaps, a better idea might be to vary x from -r to r.

Categories

Find more on Vehicle Scenarios in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!