Mathematical operations in Matlab and the point

The point of this post is to talk about doing mathematics in Matlab. This is an extension of our previous post on Kickstarting Matlab. You will learn how to use all mathematical operators and get to understand your Matlab second best friend (after the profiler) : the point or dot operator. We also briefly talk a little bit about Matlab history. My only hope is that after this, you will get the point.

Matlab is full-fledged programming language now. But back in the original days, it was mainly a gigantic calculator for crunching numbers. As each release passed, it was iteratively extended to included GUIs, Object-Oriented Programming, or more advanced functions. The list of all functions available in the first Matlab, as stated by one of its creator Cleve Moler, were the following :

What happen when you multiply two matrices? Well, you have to remember your basic maths on that (wikipedia could help you out). The general rule is that both matrices need to have a dimension of the same length to be able to build this matrix product.

As you can see, B*A works but not A*B : Matlab follows all these well-established mathematical principles.

Let’s suppose now that you don’t want this complicated matrix multiplication. You want EVERY elements in B to be multiplied by the same corresponding element in A. Now, for this to work, B and A MUST be the exact same size. Matlab provides a very very easy way to do that : the dot operator. It works like that :

The ‘.’ modifies the operation done by the * into an element-wise multiplication : each element in A is multiplied with the corresponding element in B.

For the record, ‘*’ is the exact equivalent of the function ‘mtimes‘ in Matlab, while ‘.*’ is the equivalent of ‘times‘. I invite you to check the corresponding documentation.

In my day to day coding, I actually uses ‘.*’ much more often than ‘*’. This is a very handy operator to vectorize your code.

I am sure you will love to know that this ‘.’ trick also work with ‘/’ :

>> B./A
ans =
0.4967 1.2663
0.9805 0.8824
1.1672 0.0910

Now that we are talking about division, check this out :

>> B/A
ans =
0 3.5191 -4.2211
0 0.6222 0.4930
0 -2.0752 4.0228

>> B\A
ans =
0.7512 0.4354
0.4993 0.5758

As you can tell, B/A also work but is very different to B./A. It is basically trying to solve the equation x*A = B. Similarly B\A is trying to solve A*x= B. These are very very different operations. These are NOT element-wise operators.

A^2 is the same size as A.^2 but is quite different. Indeed A^2=A*A is very different to A.^2=A.*A. You can crash a space probe on Mars with such a programming mistake with no error message. All for the cost of one single tiny point.