# Vectorization isn’t *Always* the Best Approach in Matlab

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!

# Exporting Video from Matlab

It’s rather useful to be able to export video from Matlab of say an animated plot for later sharing. I found this SO thread rather helpful.

I had the best luck with the VideoWriter method, generic code is as follows:

``````%# figure
figure,set(gcf,'Color','white')
Z = peaks; surf(Z);  axis tight
set(gca,'nextplot','replacechildren','Visible','off');%# preallocate
nFrames =20;
mov(1:nFrames)=struct('cdata',[],'colormap',[]);%# create movie
for k=1:nFrames
surf(sin(2*pi*k/20)*Z, Z)
mov(k)= getframe(gca);end
close(gcf)%# save as AVI file,and open it using system video player
movie2avi(mov,'myPeaks1.avi','compression','None','fps',10);
winopen('myPeaks1.avi')
``````

Depending on what you actually want to capture, you may need to choose a different handle, in my case I used the handle of the figure itself so I could also get the axes and the text I used for output displays.

Using this technique, andĀ this code, I was able to make a video of my prototype 1D DG code.