Which is faster, logical indexing vs for loop

22 visualizaciones (últimos 30 días)
Aly Elhefny
Aly Elhefny el 19 de Mzo. de 2020
Comentada: Raynier Suresh el 24 de Mzo. de 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 ?
  4 comentarios
Stephen23
Stephen23 el 19 de Mzo. de 2020
Editada: Stephen23 el 19 de Mzo. de 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.
Star Strider
Star Strider el 19 de Mzo. de 2020
@Aly Elhefny — My pleasure!

Iniciar sesión para comentar.

Respuestas (1)

Raynier Suresh
Raynier Suresh el 23 de Mzo. de 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 comentarios
Stephen23
Stephen23 el 23 de Mzo. de 2020
Editada: Stephen23 el 23 de Mzo. de 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:
Raynier Suresh
Raynier Suresh el 24 de Mzo. de 2020
yes, you are right

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by