I made some tests on a slightly different example (you can easily adapt to your need): I generate a 53534x3 random matrix in Matlab (7.9.0)
R = rand(53534,3);
and I try to extract those row indices where all the three coordinates are greater than 0.5. I made a first version with a loop:
I1=[];
for i=1:53534
if ( R(i,1)>0.5 && R(i,2)>0.5 && R(i,3)>0.5 )
I1 = [I1; i];
end
end
and a second version without loop but with the find
function
I2 = find( (R(:,1) > 0.5) .* (R(:,2)> 0.5) .* (R(:,3)>0.5) )
(The element-wise product replaces the AND here). Both codes give exactly the same results.
Now the interesting part is the time required for both codes to run:
- The version with loop takes around 0.05 secondes
- The version without loop takes around 0.004 secondes
So, there is one order of magnitude between them! So, at least in my example, the loop was not the most efficient implementation.
One could argue that you have more flexibility with the loop. For example, if you know that there will be only one index, you can run the loop only until you find it (not until the end). However, this makes you win (in average) only a factor 2, and the find
function has also something similar (check the help).
for
loops. Second rule of MATLAB: avoidfor
loops. $\endgroup$