4

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!

2
  • I suggest you don't use length as a variable name (or maybe that was a typo) Commented Oct 9, 2012 at 12:07
  • use Matlab's FEX Consolidator? mathworks.com/matlabcentral/fileexchange/8354 Commented Oct 9, 2012 at 14:42

1 Answer 1

7

&& 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
Sign up to request clarification or add additional context in comments.

1 Comment

@robguinness: I implemented your proposed edit that was (IMO wrongly) rejected. Thanks for spotting this!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.