An effective way to limit the matrix within the given values

I am working on a large Matlab test node with thousands of lines of code, and I am trying to optimize the most time-consuming procedures defined through the Matlab profiler. I noticed that one of those most labor-intensive operations is as follows:

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

Specifically, I have a large list of coordinates (at least 50,000 x 2), and I want to limit the values ​​of this list to save only those points that check both of these conditions: the list (:, 1) must be within [condxMin, condxMax] and list (: 2) inside [condyMin condyMax].

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

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

Thank you in advance for your reply :)

+6
source share
1 answer

The initial vector version seems to be the fastest way I can find, with the exception of any really smart ideas. Matlab does a short circuit, but not for matrices. The implementation of the loop that you showed will be very slow, since you do not pre-allocate (and you cannot pre-allocate the full matrix).

I tried several variations of this, including the for loop, which used the && short circuit to determine if the index was bad or not, but there is no such luck. On the plus side, the vector version you received has 0.21 s for a list of coordinates of 5 million elements.

+1
source

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


All Articles