Efficient Vectorization of For Loop

조회 수: 2 (최근 30일)
Shreyas Bharadwaj
Shreyas Bharadwaj 2024년 4월 15일
댓글: Shreyas Bharadwaj 2024년 4월 16일
Hi,
I have three matrices and C and am trying to compute a fourth matrix Min the following way:
for p = 1:N
for q = 1:N
M(p,q) = 2 * sum(A(:,q) .* conj(B(:,p)) .* C(:,q));
end
end
All matrices are . I am trying to compute this for N = 750 or so and the computation is extremely slow. I cannot find any obvious way to vectorize the code. Any help would be very much appreciated.
Thanks.

채택된 답변

Bruno Luong
Bruno Luong 2024년 4월 15일
편집: Bruno Luong 2024년 4월 15일
Not tested but the sign reading tell me
M = 2*B' * (A.*C);
  댓글 수: 4
James Tursa
James Tursa 2024년 4월 15일
편집: James Tursa 2024년 4월 15일
I would guess that having 2*B' at the front will force MATLAB to physically compute the conjugate transpose of B first. However, if you segregate the 2* operation as 2 * (B' * (A.*C)), the B' would not need to be physically formed to do the conjugate transpose matrix multiply since this will be handled by flags passed into the BLAS routine. Maybe a bit faster? E.g.,
A = rand(5000); B = rand(5000); C = rand(5000);
timeit(@()2*B' * (A.*C))
ans = 0.5515
timeit(@()2*(B' * (A.*C)))
ans = 0.4901
Shreyas Bharadwaj
Shreyas Bharadwaj 2024년 4월 16일
Thank you!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Solver Outputs and Iterative Display에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by