next up previous contents
Next: Advanced data types in Up: A Practical Introduction to Previous: Solving nonlinear problems in

Efficiency in Matlab

User-defined Matlab functions are interpreted, not compiled. This means roughly that when an m-file is executed, each statement is read and then executed, rather than the entire program being parsed and compiled into machine language. For this reason, Matlab programs can be much slower than programs written in a language such as Fortran or C.

In order to get the most out of Matlab, it is necessary to use built-in functions and operators whenever possible (so that compiled rather than interpreted code is executed). For example, the following two command sequences have the same effect:

>> t = (0:.001:1)';                            
>> y=sin(t);
and
>> t = (0:.001:1)';
>> for i=1:length(t)                                       
     y(i) = sin(t(i));
   end
However, on my computer, the explicit for-loop takes 46 times as long as the vectorized sine function.



Mark S. Gockenbach
Wed Sep 8 10:44:13 EDT 1999