robguinness
robguinness

Reputation: 16656

How to perform a "find" in Matlab using multiple parameters?

I'm looking for a way to "vectorize" the following code. That is, I want to get rid of the for loop, which is taking a long time (this for loop is nested in another for loop that repeats 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

I tried at first to use the Matlab find function (e.g. 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 of && are not scalar, this doesn't work. Any ideas on how to do this would be most appreciated!

Upvotes: 4

Views: 2557

Answers (1)

Jonas
Jonas

Reputation: 74940

&& and || work only for scalar comparisons, as you've noticed. & and | work on vectors, though. Note that you don't even need find:

idxUL = coords(:,1) <= 4 & coords(:,2) <=8;
idxUR = coords(:,1) > 4 & coords(:,2) <=8;

upperLeft = coords(idxUL,:);
upperRight = coords(idxUR,:); %# etc

Upvotes: 7

Related Questions