Which is faster, logical indexing vs for loop
26 views (last 30 days)
Show older comments
Hello everyone,
I'm currently constructing a code that would run for extremly big data arrays so I'm currently working on minimizing my code's computational time to minimum. And my question is: Which of the following will be faster for matlab
- To run a foor loop for the arrays element by element and applying if conditions at each cycle to give an output.
- or use logical indexing and apply the different if conditions to groups following same criteria. (ex, r = find ( a>8)).
In other words, is it faster to run a for loop along the array or to logical index scan it about 10 times ?
4 Comments
Stephen23
on 19 Mar 2020
Edited: Stephen23
on 19 Mar 2020
Exactly how big are your "extremly big data arrays" ?
It is possible that creating a large logical array via logical indexing could be slower than a loop. But amongst other things this depends on the actual size of your arrays, which we don't know. We also don't know what your system specifications are.
Answers (1)
Raynier Suresh
on 23 Mar 2020
To find the time taken by a certain piece of code you could use the “tic toc” or “timeit” or “cputime”. The below code is an example which can tell you whether the logical indexing or “find” command is faster.
a = 10:20;
tic
r = find(a>14);
toc % Time taken by find command to find index of elements greater than 14
r1 = [];
tic
for i=1:numel(a)
if a(i)>14
r1 = [r1 i];
end
end
toc %Time taken to find index of elements greater than 14 by indexing
Refer to the links below for more details:
2 Comments
Stephen23
on 23 Mar 2020
Edited: Stephen23
on 23 Mar 2020
"The below code is an example which can tell you whether the logical indexing or “find” command is faster."
The code does not use logical indexing.
Logical indexing is explained in the MATLAB documentation, blogs etc.:
Logical indexing is where a logical array is used as an index, e.g.:
idx = [some logical array]
B = A(idx)
There is no code given in this answer that matches the definition of logical indexing.
"%Time taken to find index of elements greater than 14 by indexing "
This loop timing will be distorted by the lack of array preallocation:
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!