Is it possible to vectorize this loop?

조회 수: 20 (최근 30일)
Adam Frej
Adam Frej 2020년 11월 30일
편집: Jan 2020년 11월 30일
A = rand(1, 100);
B = rand(1, 100);
w = 0;
for i = 1:length(A)
w = w + A(i).*B;
end

채택된 답변

Stephan
Stephan 2020년 11월 30일
w_new = (sum(w + A.*B(:),2))';
  댓글 수: 1
Adam Frej
Adam Frej 2020년 11월 30일
Good answer. It can be simplified to:
w_new = (sum(A'*B))

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2020년 11월 30일
편집: Jan 2020년 11월 30일
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.

카테고리

Help CenterFile Exchange에서 Statistics and Machine Learning Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by