why my vectorized code perform weaker than unvectorized one?
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
David Young
le 3 Août 2014
Modifié(e) : David Young
le 3 Août 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
le 4 Août 2014
Modifié(e) : per isakson
le 4 Août 2014
"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.
Réponses (1)
the cyclist
le 3 Août 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.
0 commentaires
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!