# Vect tip of the Week : Addition of matrices

This is a new series of posts which will run along with the “fourier awesomeness” ones. Before one or two days, I was with a colleague and we were trying to program something in Matlab, when I said something about “vectorizing” the code, to which I got a blank stare as an answer.

So, since Matlab is one of the most useful tools in a scientist’s arsenal, I thought that I could once a week post a tip about vectorizing your code. But I still have not told you what vectorizing is.

Let’s say that you this problem. You have to matrices A and B, both square and of size $m\times m$ which you want to add. Naturally, if you are used to writing code in a programming language like C, Fortran, then you already have formed the algorithm in your head. Something like,

For i = 1 to n
For j = 1 : n
sum[i][j] = A[i][j] + B[i][j];
end
end

which means that we run through every element of the two matrices from the left to the right and from the top to the bottom, add them and keep the result to the variable sum.

Now, Matlab provides us with the commands to code however we like. If we want to code the earlier example in Matlab, then that is simply

sum = 0;
for i = 1 : n
for j = 1 : n
sum(i,j) = A(i,j) + B(i,j);
end
end

And here is the beauty of Matlab. There is a better, more efficient way to do it which also is more intuitive and makes writing code easier. We can just write,

sum = A + B;

The result of that statement is to add very fast the elements of A with the corresponding elements of B and then store them into a the new matrix “sum”.  Matlab has the capability of handling operations between matrices and vectors in a very clean and concise way. It also makes a big difference in performance. Using for and while loops may be OK when using a low level language like C but when coding Matlab, writing everything as operations between matrices or vectors will make your code that much faster and shorter, occasionally sacrificing clarity. Vectorization is the act of turning your code from loop-based to one that uses a lot of matrix operations. Sometimes, as in the previous case, things are simple. In either cases, there is an obstacle in the way that makes vectorization difficult. However, if your code doesn’t involve a lot of recursion, there is a good chance that you can make it run faster this way.

So, I hope that this series of posts will be useful to people that use matlab a lot!

Until next time.