about nested for loop

1 次查看(过去 30 天)
t g
t g 2012-5-19
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.

回答(2 个)

Teja Muppirala
Teja Muppirala 2012-5-20
D=sum(sum(B.*(C*A*C')))

Walter Roberson
Walter Roberson 2012-5-19
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?

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by