Link to home
Start Free TrialLog in
Avatar of gkatz
gkatz

asked on

MATLAB loop speed

I am currently programming some large scripts in matlab.  I have discovered that when using 'while' loops, or 'for' loops, etc. the processing time increases almost exponentially.  
I am looking for why loops greatly slow down the program in matlab and how to fix it without taking out the loops and just copying and pasting the code out.  Any help would be greatly appreciated.

-gkatz
ASKER CERTIFIED SOLUTION
Avatar of sunnycoder
sunnycoder
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of alexandros
alexandros

First of all remember that every variable in Matlab is saved as an array. That means matlab is designed for matrix and vector calculations.  It is very important to try to vectorize your code in order to make it run faster, actually very faster. Unlike compiled languages, matlab interprets each line in a for loop on each iteration of the loop. Most loops can be eliminated by performing an equivalent operation using matlab vectors. Sometimes this is very easy to do and it is a great gain speed.

e.g.
for i=0:0.1:1000
      y(i*10+1)=sin(i);
end

would run much faster if you wrote it as:

i=0:0.1:1000
y=sin(i);

O.K. this is a simple example but i do not want to copy/paste matlab help book here. Search for improoving performance and vectorizing loops in matlab documentaion. There you `ll find more complicated examples and which functions to use in order to achieve your goal.

Remember also that functions are executed much faster than scripts. So a "lazy solution" to accelerate your programs would be to write the code inside your loops as a function. Remember though that this won`t work as well as vectorizing your loops.
Avatar of gkatz

ASKER

Thanks guys for your quick response, after continuing to work on my code I found that my problem was actually in calling a function that was being passed an array.  Matlab does not reference the array like C or C++ so that was slowing down the program.  Both made good points and I found the links to be very interesting.  Thanks again.
Gkatz