about nested for loop

1 view (last 30 days)
t g
t g on 19 May 2012
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.

Answers (2)

Teja Muppirala
Teja Muppirala on 20 May 2012
D=sum(sum(B.*(C*A*C')))

Walter Roberson
Walter Roberson on 19 May 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?

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!