How to speed up my while loops

23 views (last 30 days)
Felix Lauwaert
Felix Lauwaert on 1 Aug 2015
Edited: Cedric Wannaz on 2 Aug 2015
I have been looking for ways to speed up my code because sometimes I spend some hours at running once MATLAB. I've read: But it's all about "for" loops (spectacular post, BTW). The problem is that I mainly have "while" loops so I don't get how could I vectorize them. The main problem is that I call another function I've made inside my "while" loop, and that function has another "while" which calls another function with another "while".
I would appreciate any tip. Here you have part of one of my functions, if you want an example:
PSspan = [t0 t0+increment];
[resu] = nInt(ab,PSspan,hmax,tol);
[resu] = ham(resu);
[resuPol] = convPol(resu);
while iPS<nPS && loop<loopLimit
loop=loop+1; if mod(loop,250)==0; display(loop); end
t0=resu(1,end); PSspan=[t0 t0+increment];
[resu] = nInt(ab,PSspan,hmax,tol);
[resu] = ham(resu);
[resuPol] = convPol(resu);
%Comprovació de si s'ha arribat a PS per thetaP
switch tipusCoord
case 'Cartesianes';
case 'Polars';
if p*q<0 && ctrl>0
%Poincaré section
iPS=iPS+1; display(iPS); loop=0;
[ coordCart, coordPol ] = BiseccioMod( resu , hmax, tipusCoord, variablePS );
resuPS(:,iPS)=coordCart; resuPSPol(:,iPS)=coordPol;
Felix Lauwaert
Felix Lauwaert on 2 Aug 2015
You're probably right. I'll have a better look at parfor, although I've allready used it a little. Thanks

Sign in to comment.

Accepted Answer

Jan on 1 Aug 2015
Edited: Jan on 1 Aug 2015
Why do you assume, that the while loop needs a remarkable amount of time in your code? The profiler will reveal, which lines or subfunctions require the most time. When the loop itself takes a few percent of the processing time only, an optimization is not efficient.
Matlab's JIT acceleration is impeded, if lines contain more than one command. Therefore and to improve the readability, use one command per line only.
Jan on 2 Aug 2015
An integration with 1.9e6 function calls is suspicious. Do you integrate over a very long period of time or are the integration tolerances set to tiny values? In both cases the accumulated rounding errors must be taken into account and dominate the local discretization errors. Another problem could be, that the function to be integrated is stiff, while your ODE78 solver is designed for non-stiff functions. This would affect the accuracy severely. Or you have discontinuities in the function and the stepsize control fails.
So you see, that there can be many sources for a slow processing time apart from the old rumor, that Matlab processes loops slowly.

Sign in to comment.

More Answers (0)


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!