Is there a way to vectorise this vector/matrix product?

조회 수: 1 (최근 30일)
Daniel Pollard
Daniel Pollard 2021년 5월 7일
답변: Bruno Luong 2021년 5월 7일
I have a piece of code inside a for loop, which looks like
for k = 1:size(G, 1)
G(k) = real(W(:,k)' * R * W(:,k))
end
G is preallocated (which is how I know the length of it). W and R are 2D matrices (so W(:,k) is a vector). This loop is a real bottleneck in my code, that one line taking 90% of the total time that it takes to run a script which itself calls other functions and files. It's not possible to use a parfor loop as I'm already using one in a wrapper function.
Is there a way to vectorise that loop, in order to reduce the number of times the calculation is done? I'm sure it can be done, but it's not at all obvious to me.

채택된 답변

Matt J
Matt J 2021년 5월 7일
편집: Matt J 2021년 5월 7일
G=real( sum((R*W).*conj(W),1) );
  댓글 수: 4
Matt J
Matt J 2021년 5월 7일
Here is a test of a agreement with random data:
N=5;
W=complex(rand(N),rand(N));
R=complex(rand(N),rand(N));
%%% Original method
G=nan(N,1);
for k = 1:size(G, 1)
G(k) = real(W(:,k)' * R * W(:,k));
end
Gbase=G;
%%% Proposed alternative
G=real( sum((R*W).*conj(W),1) ).';
Discrepancy=norm(G-Gbase,'fro')
Discrepancy = 1.9860e-15
Daniel Pollard
Daniel Pollard 2021년 5월 7일
You're right, and I just came back to your answer to say that. Thank you!

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

추가 답변 (1개)

Bruno Luong
Bruno Luong 2021년 5월 7일
G = real(dot(W,R*W,1)).';

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by