Which is faster, logical indexing vs for loop
22 次查看(过去 30 天)
显示 更早的评论
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
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.
回答(1 个)
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
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:
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!