why my vectorized code perform weaker than unvectorized one?
조회 수: 11 (최근 30일)
이전 댓글 표시
i use "find" function to speed up the code, but surprisingly enough the vectorized code is slower than unvectorized one! i ran them in matlab 2013!
function y = exam8(x)
% Computes the sinc function per ? element for a set of x values.
y = ones(size(x)); % Set y to all ones, sinc(0) = 1
for k =1: length(x)
if x(k)~=0
y(k) = sin(x(k)) ./ x(k);
end
end
% vectorized code
function y = exam9(x)
% Computes the sinc function per ? element for a set of x values.
y = ones(size(x)); % Set y to all ones, sinc(0) = 1
i = find(x ~= 0); % Find nonzero x values
y(i) = sin(x(i)) ./ x(i); % Compute sinc where x ˜= 0
end
댓글 수: 3
David Young
2014년 8월 3일
편집: David Young
2014년 8월 3일
I also find the loop is fastest, even using logical indexing for the vectorised version (release 2013b under Windows). It's surprising because in the documentation we read that "Vectorized code often runs much faster than the corresponding code containing loops." If this doesn't apply to jabbar-kamali's example, it would be useful to have more guidance as to when it does apply.
per isakson
2014년 8월 4일
편집: per isakson
2014년 8월 4일
"it would be useful to have more guidance"   I definitely agree!   AFAIK: There are some fragmented guidance scattered all over the place, but no in-depth treatment of the topic. A quick search returned these two blog posts by Loren:
- Speeding Up MATLAB Applications
- Piecewise Linear Interpolation
- And there are hundreds of book to look in.
답변 (1개)
the cyclist
2014년 8월 3일
Here is another algorithm. (Notice that you don't need the preallocation step in this one.)
y = sin(x) ./ x;
y(isnan(y)) = 1;
The relative performance of the three algorithms is quite dependent on the proportion of zeros in your input.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!