Improving performance of for loop and function calls

9 views (last 30 days)
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

Accepted Answer

Image Analyst
Image Analyst on 23 Feb 2014
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 Comment
suraphim
suraphim on 2 Mar 2014
@Image analyst, Thanks alot! there is pretty good difference by switching the order. Am also trying to apply vectorization..to push further the optimization.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!