필터 지우기
필터 지우기

Why is loop time execution better than vectorized form in this case?

조회 수: 1 (최근 30일)
Adriano
Adriano 2011년 7월 27일
Hello everyone,
At first, I had the following code:
for ii = 1:numel(data.classes)
switch data.classes{ii}
case 1
data.classes{ii} = 'case 1';
% Active classes
case 2
data.classes{ii} = 'case2';
otherwise
disp('Invalid case.');
end
end
However, I know that vectorized code is preferred instead of loops, so I changed it to
case1Found = ismember(data.classes, case1Members);
case2Found = ismember(data.classes, case2Members);
data_.classes(case1Found) = {'case1'};
data_.classes(case2Found) = {'case2'};
When comparing their performance (execution time) I was surprised to see that the first option, with loops was twice as fast than the vectorized option (0.014688 s vs. 0.029204 s)!
Why is this? Thanks ;-) !

채택된 답변

Jan
Jan 2011년 7월 27일
ISMEMBER is powerful and in consequence time consuming. It performs one or two sortings of the inputs, which is inefficient for large data sets (_large_ means e.g. 1e3 or 1e6 elements). For small data sets (10 elements) the overhead of ISMEMBER is more important.
You can run the PROFILEr to see, which lines cause the most computing time.

추가 답변 (1개)

Daniel Shub
Daniel Shub 2011년 7월 27일
The gains in efficiency from vectorization are not always that substantial anymore (and can even be negative) since loops in MATLAB have become much faster over the years, thanks, I believe, to the JIT accelerator.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by