why my vectorized code perform weaker than unvectorized one?

1 view (last 30 days)
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 Comments
David Young
David Young on 3 Aug 2014
Edited: David Young on 3 Aug 2014
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 on 4 Aug 2014
Edited: per isakson on 4 Aug 2014
"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:

Sign in to comment.

Answers (1)

the cyclist
the cyclist on 3 Aug 2014
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.

Community Treasure Hunt

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

Start Hunting!