why my vectorized code perform weaker than unvectorized one?

11 visualizaciones (últimos 30 días)
jabbar kamali
jabbar kamali el 3 de Ag. de 2014
Editada: per isakson el 4 de Ag. de 2014
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 comentarios
David Young
David Young el 3 de Ag. de 2014
Editada: David Young el 3 de Ag. de 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 el 4 de Ag. de 2014
Editada: per isakson el 4 de Ag. de 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:

Iniciar sesión para comentar.

Respuestas (1)

the cyclist
the cyclist el 3 de Ag. de 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.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by