about nested for loop
조회 수: 1 (최근 30일)
이전 댓글 표시
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.
댓글 수: 0
답변 (2개)
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?
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!