Monthly Archives: July 2014

[Matlab Trick] Permute

In the previous post, I introduced the problem of converting a three dimensional matrix (1xmxp) to a two dimensional matrix of size mxp using the squeeze function of matlab. In this post I am introducing a new solution, using function permute.
If you have read the previous post, you can jump directly to solution 2.

The Problem: I was given a three dimensional matrix (1xmxp), I need to convert it to a two dimensional matrix of size pxm.
The Trivial Solution: Nested loop. In addition to the time complexity, the solution make me feel like a dummy.

What I did instead: After 5 mins of google search, I found out a couple of solutions that I found helpful. I will share these with you below.

Let me explain with a concrete example. We need to generate a three dimensional matrix first, say size 1x3x4.

mat(:,:,1)=[1 2 3];
mat(:,:,2)=[4 5 6];
mat(:,:,3)=[7 8 9];
mat(:,:,4)=[10 11 12];

The goal is to convert this into a two dimensional matrix of size 4×3. The new matrix should look like the following:

new_mat =
[1 2 3;
4 5 6;
7 8 9;
10 11 12;]

Solution 1: Squeeze.
This is explained in the previous post.

Solution 2: Permute and Reshape

 new_mat = permute(mat,[3 2 1]);
 % function permute rearranges the dimensions of matrix mat 
 % The order of the rearrangement is specified in the second argument
 % In this example, the third dimension and the first dimension was swapped.

The resulting matrix is just what we wanted :)