Have you vectorised your MATLAB code?
28 May 2021
By David Warne, a former QCIF eResearch Analyst at QUT.
MATLAB is a powerful programming environment for scientific applications. It is designed to be highly optimised for matrix and vector mathematical operations. Writing code in a way that leverages these matrix operations is known as vectorising code. There are many reasons why a particular piece of MATLAB code is running slow, but low usage of vectorised code is one of the most common ones that I see.
The differences between vectorised and non-vectorised code can be substantial. Consider a somewhat contrived example of matrix multiplication; a direct MATLAB implementation would be:
Now, compare the runtime of the above code to MATLAB’s in-built matrix multiply for two 1000 x 1000 matrices (using a two-year-old Core i7 laptop):
The in-built matrix mathematics is around 250x faster than direct MATLAB! There are lots of reasons for this, but for now, let’s just leave it at that.
Admittedly, this example is a bit artificial, but the point is to emphasise the potential computational gain that can be achieved through ensuring your code is as vectorised as possible. This may require a little more coding effort, but the results are well worth it.
For more details and examples, check out the following MATLAB documentation page.
This article was first published on 09/11/2017.