Reputation: 41
I have a matrix which is 256x938. I need to go through each individual element, see if it is in the range -pi < element < pi, if it is not then we need to subtract or add a multiple of 2*pi to get the element in the range. Preferrably without for loops as we have found that they are very inefficient.
Upvotes: 4
Views: 103
Reputation:
Not unlike the other solutions posed, but a bit cleaner since it requires only one simple line of code...
B = mod(A+pi,2*pi) - pi;
A = -20:2:20;
mod(A+pi,2*pi) - pi
ans =
Columns 1 through 12
-1.1504 0.84956 2.8496 -1.4336 0.56637 2.5664 -1.7168 0.28319 2.2832 -2 0 2
Columns 13 through 21
-2.2832 -0.28319 1.7168 -2.5664 -0.56637 1.4336 -2.8496 -0.84956 1.1504
Upvotes: 4
Reputation: 9313
I don't have Matlab at hand right now, so my suggestion might not work, but I hope the idea will.
Try something along this way:
c = cos(B); % will set all your elements between [-1 1]
B2 = acos(c); % will return values between [0 PI] but for some the sign will be wrong
B2 = B2.*sign(sin(B)); % should set the correct sign for each element.
Hope this works.
I could have condensed all three lines to 1, but I tried to make the idea as clear as possible.
Upvotes: 0
Reputation: 7805
Is this what you want?
B=rem(A,2*pi)
B(A<-pi)=A(A<-pi)+2*pi
B(A>pi)=A(A>pi)-2*pi
Every element b
in B
is now -pi <= b <= pi
.
It can not become -pi < b < pi
as asked for in the question.
Upvotes: 1