How to perform a “search” in Matlab using several parameters?

I am looking for a way to "vectorize" the following code. That is, I want to get rid of the for loop, which takes a lot of time (this for the loop is nested in another loop repeating more than 40,000 times).

for k=1:length if coords(k,1)<=4 && coords(k,2) <=8 upperLeft(countUL,:) = coords(k,:); countUL=countUL+1; end if coords(k,1)>4 && coords(k,2) <=8 upperRight(countUR,:) = coords(k,:); countUR=countUR+1; end if coords(k,1)>4 && coords(k,2) >8 lowerRight(countLR,:) = coords(k,:); countLR=countLR+1; end if coords(k,1)<=4 && coords(k,2) >8 lowerLeft(countLL,:) = coords(k,:); countLL=countLL+1; end end 

At first I tried to use the Matlab find function (for example, find(coords(k,1)<=4) ), but in my case I have two parameters that I need to “find”. I tried something like find(coords(:,1)<=4 && coords(:,2)<=8) , but since the && operands are not scalar, this does not work. Any ideas on how to do this would be greatly appreciated!

+4
source share
1 answer

&& and || only work for scalar comparisons, as you have noticed. & and | work on vectors. Note that you do not even need to find :

 idxUL = coords(:,1) <= 4 & coords(:,2) <=8; idxUR = coords(:,1) > 4 & coords(:,2) <=8; upperLeft = coords(idxUL,:); upperRight = coords(idxUR,:); %# etc 
+7
source

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


All Articles