Efficient Vectorization of For Loop
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Shreyas Bharadwaj
am 15 Apr. 2024
Kommentiert: Shreyas Bharadwaj
am 16 Apr. 2024
Hi,
I have three matrices
and C and am trying to compute a fourth matrix Min the following way:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1669666/image.png)
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1669671/image.png)
Thanks.
0 Kommentare
Akzeptierte Antwort
Bruno Luong
am 15 Apr. 2024
Bearbeitet: Bruno Luong
am 15 Apr. 2024
Not tested but the sign reading tell me
M = 2*B' * (A.*C);
4 Kommentare
James Tursa
am 15 Apr. 2024
Bearbeitet: James Tursa
am 15 Apr. 2024
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))
timeit(@()2*(B' * (A.*C)))
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!