Improving performance of for loop and function calls

5 次查看(过去 30 天)
I have this matlab code as part of my matlab project, as the info. i got from the 'profreport' most of the time is spent in the 'while' line. any help regarding how can i improve the efficency. or generally how can i make the for loops more efficient. Thank you!
% p is 2D matrix of big size
s=size(p); pp=p; p=zeros(s(1),s(2));
while(norm(p-pp)>0.05 )
p=pp;
for n=1:N
z=0;
for miu=1:C
z = z + p(n,miu) * funQ(n,miu,p,R,N,C); % call function funQ
end
for lambda=1:C
pp(n,lambda) = (p(n,lambda) * funQ(n,lambda,p,R,N,C))/z; % call function funQ
end
end
end

采纳的回答

Image Analyst
Image Analyst 2014-2-23
Try switching the order. MATLAB likes to go down rows first, then over to the next column and down its rows. So you want the inner index to be the inner iterator. So swap the order of the loops over miu and n. Have n be the inner loop. See if that's any faster. A for loop by itself is pretty fast -- I can do tens of millions of iterations in a fraction of a second. What can take time is accessing the memory and if adjacent iterations need to access far flung memory locations, then that's what will slow it down. It's faster if the next memory location it needs is close to the one you accessed last.
  1 个评论
suraphim
suraphim 2014-3-2
@Image analyst, Thanks alot! there is pretty good difference by switching the order. Am also trying to apply vectorization..to push further the optimization.

请先登录,再进行评论。

更多回答(0 个)

类别

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