Optimizing your code


Source : Image

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. Make sure you use the right data type for your variables. Bigger data types are more demanding on memory and CPU. Check my post on data conversion if needed.
  3. 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.
  4. Vectorize your code, whenever possible.
  5. Pre-allocate your memory.
  6. Make a reasonable number of calls to all graphic displays command, in particular limit your calls to the waitbar.
  7. Use sparse matrix if applicable.
  8. 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.
  9. 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.
  10. Sometimes global or persistent variables can be a memory saving solution
  11. Understand that Matlab organize its arrays as Column-major and adjust your code accordingly.
  12. 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.
  13. 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 to pavlovsr Cancel reply

Your email address will not be published. Required fields are marked *