How to select individual elements of a given (very large) matrix, see if they are in a certain range and change them in Matlab?

I have a 256x938 matrix. I need to go through each individual element, see if it is in the range -pi <element <pi, if it is not, we need to subtract or add a multiple of 2 * pi to get an element in the range. Preferably without loops, as we have found that they are very inefficient.

+4
source share
3 answers

Unlike other solutions, but a little clean, because 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 
+4
source

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 

Each element of b in b now -pi <= b <= pi .

It cannot become the -pi < b < pi requested in the question.

+1
source

I don’t have Matlab right now, so my suggestion may not work, but I hope the idea will be.

Try something along this path:

 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 compress all three lines to 1, but I tried to make this idea as clear as possible.

0
source

Source: https://habr.com/ru/post/1446099/


All Articles