Saturday, October 2, 2010

Multidimensional matrices operations: Matlab mtimesx

Hi guys,

today it's the first time I'm writing about something concerning the world of engineering. In particular we are talking about matlab: an awsome platform for computing. Imagine a swiss-knife with easy high-level programming language, GUIs, rapid and optimized libraries, data importing, terminal board connection, graphig drawing, 3d animation, system terminal interface and lots of toolbox developed by users from all over the world: this is Matlab.

When I heard the first time that name at university I was not happy to learn another programming language more than C++, but time made me change my mind. Now that program is the base to do any sort of thing in my working environment. A brief look at my work is some 3-d processing on a set of slices coming from MRI (Magnetic Resonance Imaging), and believe the results are amazing.

Sometimes when programming it is obvious to introduce a for loop. In matlab this is nothing but slow. It might be useful for a first stub of the algorithm, but loops are really too slow, due to the literal translation and execution of the code each time the loop cycles. To avoid that loss of time and to use the power of both (or all) the cores there are some smart solutions: one of them is certainly mtimesx.

Mtimes is the default function to execute matrix product and division. This is a good solution to replace a loop as the operation is readed once, the libraries are compiled in C, and the procedure is optimized.

This is true, but not the best one can do. For example you might need to use 3D matrices: mtimes supports just 2D operations, so you should employ a loop. What I mentioned above now comes to light: there is a multi-dimensional martices support developed from James Tursa, mtimesx. It requires some compilation in Matlab (nothing for a gentoo user), all documented in its guide. That function, not only enables ND matrices product, but is faster than mtimes in many cases (look at image).

The result is amazing, I experienced a serious reduction of time (maybe an order). Just a little note. If you work with 3D matrices, ok, but going over 3D is risky: in our world we can experience a 3+D environment (time is not really the 4th dimension), so even if employing a 4D or 5D algorithm can be faster than ever, remember that programming it and debugging it might be seriously complicated.

Good luck.


  1. This is perfect it was what I was looking for, because it provided me all the techniques and applications in order to do all things I was looking for.