Is it possible to vectorize this loop?

 Akzeptierte Antwort

Stephan
Stephan am 30 Nov. 2020

0 Stimmen

w_new = (sum(w + A.*B(:),2))';

Weitere Antworten (1)

Jan
Jan am 30 Nov. 2020
Bearbeitet: Jan am 30 Nov. 2020

1 Stimme

A = rand(1, 1000);
B = rand(1, 1000);
tic
for k = 1:1000
w = 0;
for i = 1:length(A)
w = w + A(i).*B;
end
end
toc
tic
for k = 1:1000
w = (sum(A .* B(:),2))';
end
toc
tic
w = 0;
for k = 1:1000
w = sum(A' * B);
end
toc
I get the timings (Matlab online!):
0.34 seconds
0.69 seconds
0.41 seconds
So check it on your machine is the vectorization is an advantage.

Kategorien

Mehr zu Statistics and Machine Learning Toolbox finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 30 Nov. 2020

Bearbeitet:

Jan
am 30 Nov. 2020

Community Treasure Hunt

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

Start Hunting!

Translated by