Take the 2-minute tour ×

I am working on a big Matlab testbench with thousands of lines of code, and I am trying to optimize the most time-consuming routines, determined via the profiler in Matlab. I noticed that one of those most time-consuming operations is the following:

list = list((list(:,1) >= condxMin) & (list(:,1) <= condxMax) & (list(:,2) >= condyMin) & (list(:,2) <= condyMax),:);

Concretely, I have a big list of coordinates (50000 x 2 at least) and I want to restrict the values of this list so as to keep only the points that verify both of these conditions : list(:,1) must be within [condxMin, condxMax] and list(:2) within [condyMin condyMax].

I was wondering if there was a more efficient way to do it, considering that this line of code is already vectorized. Also, I am wondering if Matlab does a short-circuiting or not. If it doesn't, then I don't think there is a way to do it without breaking the vectorization and do it with a while loop, where I would write instead something like this:

for i=1:size(list,1)
   if(cond1 && cond2 && cond3 && cond4)
      newlist(j,1:2) = list(i,1:2);

Thank you in advance for your answer :)

share|improve this question
add comment

1 Answer

Looks like the original vectorized version is the fastest way I can find, barring any really clever ideas. Matlab does do short circuiting, but not for matrices. The loop implementation you you showed would be very slow, since you're not pre-allocating (nor are you able to pre-allocate the full matrix).

I tried a couple of variations on this, including a for loop which used a short circuited && to determine whether the index was bad or not, but no such luck. On the plus side, the vectorized version you've got runs at 0.21s for a 5 million element coordinate list.

share|improve this answer
I feared there was not any other way to do it, but thanks for the clarification :) Unfortunately, this function is called more than 100k times in the whole testbench, and so most of the computation time lie in this function. I guess I don't have any other way to improve it algorithmically. –  user1638514 Aug 31 '12 at 13:03
Yeah I tried a few more things, but nothing was faster. I'm not sure what kind of testbench you're running, but if you're concerned about the time that this takes to run you should really consider filtering the values one time, saving them, and then loading the filtered values from then on. –  Salain Aug 31 '12 at 15:51
add comment

Your Answer


