Usually if you are using for() loops in Matlab for code “hotspots”, you are doing something wrong. The fastest way to solve large systems is usually to “vectorize”. Essentially you unroll your for() loop into a vector or matrix and use sneaky linear algebra tricks to solve the whole shebang in one go.

Things start to break down when you are trying to solve data in multidimensional arrays though. If a Matlab function specifically operates on 2D matrices (say for example backslash: ‘\’) and you pass it a stack of 2D arrays it will choke. You would expect it to elegantly flatten it and solve, but I haven’t found a built in way to do this.

So say you’d like to calculate the gradient of the equation of a plane prescribed by 3 points in R^3 for many such planes. I thought I would be clever and flatten these out into a large 2D sparse array and solve the whole thing in one go. I wanted to see how much faster (hah!) this would be then naively iterating through them one by one in a for() loop.

Well take a look for yourself:

Turns out it is 81 times faster to use that for() loop, significantly less complex, and much more readable!