about nested for loop

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.

Respuestas (2)

Teja Muppirala
Teja Muppirala el 20 de Mayo de 2012

2 votos

D=sum(sum(B.*(C*A*C')))
Walter Roberson
Walter Roberson el 19 de Mayo de 2012

1 voto

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?

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Productos

Etiquetas

Preguntada:

t g
el 19 de Mayo de 2012

Community Treasure Hunt

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

Start Hunting!

Translated by