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.
- First and probably most important thing, run the profiler on your code.
- 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.
- 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.
- Vectorize your code, whenever possible.
- Pre-allocate your memory.
- Make a reasonable number of calls to all graphic displays command, in particular limit your calls to the waitbar.
- Use sparse matrix if applicable.
- 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.
- 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.
- Sometimes global or persistent variables can be a memory saving solution
- Understand that Matlab organize its arrays as Column-major and adjust your code accordingly.
- 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.
- Use short-circuit operators whenever possible.