Improving performance of for loop and function calls

5 visualizaciones (últimos 30 días)
suraphim
suraphim el 23 de Feb. de 2014
Comentada: suraphim el 2 de Mzo. de 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

Respuesta aceptada

Image Analyst
Image Analyst el 23 de Feb. de 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 comentario
suraphim
suraphim el 2 de Mzo. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by