Optimizing your code

Matlab is thought to be slow by the programming community. But in my experience, every time I digged in supposedly slow code, a very few and simple tricks made it 10 times faster.

If you follow all of these posts in this order, in principle, your code should flow much faster.

  1. First and probably most important thing, run the profiler on your code.
  2. Using the profiler versus TIC/TOC (to be done).
  3. Make sure you use the right data type for your variables. Bigger data types are more demanding on memory and CPU.
  4. Understand what it means to use an interpreted programming language and look for FOR loops. But don’t over-do it as the JIT is around.
  5. Vectorize your code, whenever possible (to be continued).
  6. Pre-allocate your memory.
  7. Make a reasonable number of calls to all graphic displays command, in particular limit your calls to the waitbar.
  8. Use sparse matrix if applicable (to be done).
  9. Remember that Matlab is designed to deal with numbers and is extremely efficient at this. So it is unlikely you will be able to program faster matrix multiplication in any other language (to be done).
  10. Limit your usage of memory whenever possible. Make smart usage of Copy On Write in code and subfunctions. If possible also use In place computation. To activate it you need to follow some rules.
  11. Sometimes global or persistent variables can be a memory saving solution (to be done).
  12. Understand that Matlab organize its arrays as Column-major and adjust your code accordingly.
  13. If a matlab function is slowing your calculation down, you can Inline its code, if it is not built-in. Please take a look at a practical example of this technique.
  14. Use short-circuit operators whenever possible.

4 Responses to Optimizing your code

  1. adam says:

    thanks, really good tips!

  2. pavlovsr says:

    Awesome posts, very worthwhile!

  3. Alireza says:

    So practical tips…

  4. Rizwana says:

    Which is the best book to cover up complex structure programming in matlab. Matlab help documentation provides only basic. Suppose iam a nuance, and i know that structure are good for creating data base type application using matlab

Leave a Reply