How to vectorize the MATLAB code?
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
This is the code that I have written and I saw articles about vectorization.
N = length(a);
b = zeros(1,N - 1);
for i = 1:N-1
b(i) = a(i) + a (i + 1);
end
How should I vectorize my code in this circumstance? Any suggestions? Thank you.
0 commentaires
Réponse acceptée
Jan
le 14 Fév 2022
Modifié(e) : Jan
le 14 Fév 2022
a = rand(1, 11);
N = length(a);
b = zeros(1,N - 1);
for i = 1:N-1
b(i) = a(i) + a (i + 1);
end
% Vectorized 1:
b2 = a(1:end-1) + a(2:end);
% Vectorized 2:
b3 = conv(a, [1,1], 'valid')
% [EDITED] % Vectorized 3: Working only for even length of a!
% [EDITED] b4 = sum(reshape(a, 2, [])); % Not the same result!
% Thanks John D'Errico.
isequal(b, b2, b3)
For a = rand(1,1e6) and 100 repetitions, Matlab 2018b needs:
% Elapsed time is 0.683647 seconds. loop
% Elapsed time is 0.874940 seconds. 1:end-1 + 2:end
% Elapsed time is 0.477227 seconds. conv
You see, that vectorization is not a standard trick for accelerating code. The memory access can take more time than the loop.
3 commentaires
John D'Errico
le 14 Fév 2022
a = rand(1, 10);
b3 = conv(a, [1,1], 'valid')
% Vectorized 3: Working only for even length of a!
b4 = sum(reshape(a, 2, []));
b3
b4
b4 sums the 1st and second, but NOT the 2nd and 3rd elements.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical 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!