about nested for loop
Ältere Kommentare anzeigen
i have three matrices A,B,C of size N*N. and I have a nested for loop code as given here,
D=0;
for i=1:N
for j=1:N
for k=1:N
for l=1:N
D = D + A(k,l) * B(i,j) * C(i,k) * C(j,l);
end
end
end
end
Now for a large value of N (say N=500), this code is taking a lot of time to execute. I want to know what is the procedure to improve this code so that it executes faster.
thanks in advance for any help.
Antworten (2)
Teja Muppirala
am 20 Mai 2012
2 Stimmen
D=sum(sum(B.*(C*A*C')))
1 Kommentar
Andrei Bobrov
am 20 Mai 2012
+1
Walter Roberson
am 19 Mai 2012
B(i,j) * C(i,k) can be calculated at the "for k" level. Call that BC. Then you have simplified to
for l=1:N
D = D + BC * A(k,l) * C(j,l);
end
and that can be vectorized along l without a loop.
D = D + BC * sum(A(k,:) .* C(j,:));
After that you may be able to make further optimizations.
Can you rewrite what you are doing in terms of matrix multiplication?
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!