Speeding up a code involving nested for loops

조회 수: 9 (최근 30일)
Mehdi
Mehdi 2011년 6월 1일
[EDIT: Wed Jun 1 16:10:09 UTC 2011 - Reformat - MKF]
The following is a simplified version of a code that I need to run many times. The 'rand' function is replacing calculations that are of the same order of complexity. Any intelligent way of converting the nested loops (and the multiply-sum operation)into matrix (or faster) operations would be greatly appreciated.
M=1000;
N=1000;
PSI_conv = zeros (M,N);
PSI_ab = rand(M,N);
for s = 1 : M % M = 1000
for t = 1 : N % N = 1000
PHI_sph = rand(M,N);
PSI_conv(s,t) = sum(PSI_sph(:).* conj(PSI_ab(:)));
end
end

답변 (1개)

Sean de Wolski
Sean de Wolski 2011년 6월 1일
The idea is to minimize the number of computations inside the FOR-loop.
In this case, conj(PSI_ab(:)) doesn't change and thus only needs to be computed once. Why bother generating PSI_sph as an MxN matrix when you could just generate it as a vector and then not need the (:) operation?
M=1000;
N=1000;
PSI_conv = zeros (M,N);
PSI_ab = rand(M,N);
PSI_ab = conj(reshape(PSI_ab,numel(PSI_ab),1));
MN = M*N;
for s = 1 : M % M = 1000
for t = 1 : N % N = 1000
PHI_sph = rand(1,MN); %Edit per Jan's comment and my time test.
PSI_conv(s,t) = PSI_sph*PSI_ab;
end
end
  댓글 수: 8
Sean de Wolski
Sean de Wolski 2011년 6월 1일
The 1000^4 element matrix must take some serious time to construct. I wonder if a single for-loop and 1000^3 matrix on each iteration would be faster.
Matt Fig
Matt Fig 2011년 6월 1일
I posted a version with BSXFUN in a single loop and it was slower, so I deleted it...

댓글을 달려면 로그인하십시오.

카테고리

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