My function output has complex numbers, and I'm not using i or j. Why?
5 views (last 30 days)
Show older comments
In the file CloseFarAngles.m, I input two matrices containing x,y,z (columns 1-3) coordinate information for tracks (track identifier is in column 5). The two input variables are named close_tracks and far_tracks.
CloseFarAngles.m calculates turning angles for each track and outputs two matrices, each containing columns for the Track ID and the corresponding angles, i.e. closeangles_stored=[TrackID angles] and farangles_stored=[TrackID angles];
I am having two issues:
- I occasionally get NaN as an angles result for some coordinates, and I cannot figure out why. For example, for Track ID 106 the angle result is NaN.
- Starting at Track 107 in the closeangles_stored matrix, the results (both Track IDs and angles) are reported as complex numbers. I have checked for any usage of i or j and changed them to other variable names. I have tested other files, and partway through each closeangles_stored matrix the results contain complex numbers. None of my farangles_stored matrices ever report complex numbers.
I have included my code CloseFarAngles.m, test variables close_tracks and far_tracks, and the other functions that are called in CloseFarAngles.m (SortTracks2,HowManyTIDs,calcAngles1, FindNextTID). Please let me know if you see any obvious issues that could be causing either the NaNs or the complex numbers. Thank you.
0 Comments
Accepted Answer
dpb
on 24 Jan 2018
angle = acos(dot(a,b)/(norm(a)*norm(b)));
>> acos(2)
ans =
0.0000 + 1.3170i
>> acos(1+eps)
ans =
0.0000e+00 + 2.1073e-08i
>>
If argument to acos is outside [-1,1], even by rounding error, then you'll get complex result.
Obviously, either your input isn't proper or you've another coding error to compute the wrong a, b for at least some inputs.
Set a breakpoint in the calculation function and see where your logic goes wrong.
More Answers (1)
James Tursa
on 24 Jan 2018
Edited: James Tursa
on 24 Jan 2018
For a discussion on robust methods for calculating the angle between two vectors, see this link:
E.g.,
result = atan2(norm(cross(a,b)),dot(a,b));
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!