Which is faster, logical indexing vs for loop

조회 수: 91 (최근 30일)
Aly Elhefny
Aly Elhefny 2020년 3월 19일
댓글: Raynier Suresh 2020년 3월 24일
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
Stephen23
Stephen23 2020년 3월 19일
편집: Stephen23 2020년 3월 19일
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 2020년 3월 19일
@Aly Elhefny — My pleasure!

댓글을 달려면 로그인하십시오.

답변 (1개)

Raynier Suresh
Raynier Suresh 2020년 3월 23일
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
Stephen23
Stephen23 2020년 3월 23일
편집: Stephen23 2020년 3월 23일
"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 2020년 3월 24일
yes, you are right

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by