Improving performance of for loop and function calls

5 vues (au cours des 30 derniers jours)
suraphim
suraphim le 23 Fév 2014
Commenté : suraphim le 2 Mar 2014
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

Réponse acceptée

Image Analyst
Image Analyst le 23 Fév 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 commentaire
suraphim
suraphim le 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by