[Matlab Trick] Squeeze

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.

t = squeeze(mat) 
% the squeeze command removes the singleton dimensions
% a singleton dimension is a dimension of size 1 

t is a 3×4 matrix shown below:

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

Now we simply need to transpose it to get to our desired matrix.

new_mat = transpose(t)

One thing worth-noticing about the squeeze command: it simply removes the singleton dimensions. Applying squeeze function to matrix of size 1x3x4 (mat1 in the example below), or size 3x4x1 (mat2 in the example below), or size 3x1x4 will all result in matrix 3×4. This is illustrated below:

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

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

t1 = squeeze(mat1);
t2 = squeeze(mat2);

t1 and t2 are both 3×4, and they are exactly the same. I don’t know about everyone else, but I did not expect this to begin with.

Solution 2: Permute and Reshape
I will talk about this solution in my next blog post! see you soonish!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>