Speeding up a code involving nested for loops

10 次查看(过去 30 天)
[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