why the give code doesn't meet my requirements?
Show older comments
I want to Wrap angles to the range [-180, 180] degrees. For this I have the following code:
function wrapped_angles = wrapTo180(angles)
% Wrap angles to the range [-180, 180] degrees
wrapped_angles = mod(angles + 180, 360) - 180;
end
Likewise, I want Wrap angles to the range [-90, 90] degrees. For this I have the following code:
function wrapped_angles = wrapTo90(angles)
% Wrap angles to the range [-90, 90] degrees
wrapped_angles = mod(angles + 90, 180) - 90;
end
The 2nd function works correctly but the 1st one doesn't work correctly. Why it is so?
3 Comments
Stephen23
on 15 Sep 2024
"The 2nd function works correctly but the 1st one doesn't work correctly"
Please given an example input value and the corresponding incorrect output value.
Sadiq Akbar
on 15 Sep 2024
The interval you transform the angle to should have length 360 degrees, shouldn't it ? So I don't understand how you could transform angles uniquely to the interval [-90 90].
For the interval [-180 180], it's ok.
angles = [-182 -185 189 184];
wrapped_angle180 = mod(angles,360) - 180
wrapped_angle90 = mod(angles,180) - 90
Answers (1)
angles = [-182 -185 189 184];
rem(angles,180)
"The concept of remainder after division is not uniquely defined, and the two functions mod and rem each compute a different variation. The mod function produces a result that is either zero or has the same sign as the divisor. The rem function produces a result that is either zero or has the same sign as the dividend."
To use MATLAB mod as you wish, you would have to write your own version of rem --
sign(angles).*mod(abs(angles),180)
8 Comments
dpb
on 15 Sep 2024
The same information as above is also in the doc for mod
Sadiq Akbar
on 21 Sep 2024
mod(x,360)
restricts x to be within 0 and 360,
mod(x,360) - 180
restricts x to be within -180 and 180.
Of course, there are different ways to do with different results ( I say this just in case that you want to respond that you don't like what you get ).
u = [-35 -45 -55 35 45 55]; % 6 variables within [-180,180]
b = [30 45 55 135 245 355]; % 6 variables within [0,360]
mod(u,360) - 180
mod(b,360)
u = [-35 -45 -55 35 45 55]; % 6 variables within [-180,180]
b = [30 45 55 135 245 355]; % 6 variables within [0,360]
rem(u,180)
rem(b,360)
What would you expect the answers to be if not the above (and, more importantly, why/how do you determine that?). You can't write an algorithm until you can define the problem uniquely.
Sadiq Akbar
on 22 Sep 2024
dpb
on 22 Sep 2024
So what was/is the correct answer?
Torsten
on 22 Sep 2024
I think the correct answer is that there is no "correct" answer.
One has to decide whether to use "rem" or "mod" or some other normalization to the respective interval.
Categories
Find more on Logical 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!