Improving performance of for loop and function calls

조회 수: 5 (최근 30일)
suraphim
suraphim 2014년 2월 23일
댓글: suraphim 2014년 3월 2일
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