why my vectorized code perform weaker than unvectorized one?

10 次查看(过去 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
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
per isakson 2014-8-4
编辑:per isakson 2014-8-4
"it would be useful to have more guidance" &nbsp I definitely agree! &nbsp 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:

请先登录,再进行评论。

回答(1 个)

the cyclist
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.

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by