20. Optimizing M-Files

Society for Industrial and Applied Mathematics eBooks · 2005

Most users of MATLAB find that computations are completed fast enough that execution time is not usually a cause for concern. Some computations, though, particularly when the problems are large, require a significant time and it is natural to ask whether anything can be done to speed them up. This chapter describes some techniques that produce better performance from M-files. They all exploit the fact that MATLAB is an interpreted language with dynamic memory allocation. MATLAB has incorporated automatic optimization of code since Release 12. This is good news for users: some of the optimizations that experienced MATLAB programmers employ, and which in the past could make their code run much faster than code written by inexperienced users, are now done automatically by the MATLAB interpreter. Several aspects make MATLAB's optimization hard to understand and difficult to write about. First, the documentation is sketchy on what exactly is optimized and to what extent. Second, these capabilities are under continuing development and improve with each release. Third, some aspects of the optimization are machine-dependent, that is, they are used only on certain platforms (PC versions of MATLAB have the most comprehensive optimization). Consequently, we will say very little about MATLAB's automatic optimization and will concentrate instead on useful programming techniques, some of which can probably never be replaced by automatic optimization of code. External C or Fortran codes can be called from MATLAB via the MEX facility, provided they are augmented with a suitable gateway routine that interfaces the codes with MATLAB. The mex command is used to compile and link the C or Fortran source into a shared library that is executable from within MATLAB (and has a platform-dependent extension). See [72], [73] for details. MATLAB's profiler is a useful tool when you are optimizing M-files, as it can help you decide which parts of the code to focus on. See Section 16.3 for details. All timings in this chapter are for a 3.2Ghz Pentium 4. 20.1. Vectorization Since MATLAB is a matrix language, many of the matrix-level operations and functions are carried out internally using compiled C or assembly code and are therefore executed at near-optimum efficiency. This is true of the arithmetic operators *, +, −, \ , / and of relational and logical operators. However, for loops may be executed relatively slowly—depending on what is inside the loop, MATLAB may or may not be able to optimize the loop.

Read the paper · More papers on PaperTik