Which is faster, logical indexing vs for loop

36 views (last 30 days)
Aly Elhefny
Aly Elhefny on 19 Mar 2020
Commented: Raynier Suresh on 24 Mar 2020
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 ?

Sign in to comment.

Answers (1)

Raynier Suresh
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;
r = find(a>14);
toc % Time taken by find command to find index of elements greater than 14
r1 = [];
for i=1:numel(a)
if a(i)>14
r1 = [r1 i];
toc %Time taken to find index of elements greater than 14 by indexing
Refer to the links below for more details:

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!