Yodan
Yodan

Reputation: 13

Reshaping a matrix

I have a matrix that looks something like this:

a=[1   1   2   2   3   3   4   4;
   1.5 1.5 2.5 2.5 3.5 3.5 4.5 4.5]

what I would like to do is reshape this ie.

What I want is to take the 2x2 matrices next to one another and put them underneath each other.

So get:

b=[1     1;
   1.5   1.5;
   2     2;
   2.5   2.5;
   3     3;
   3.5   3.5;
   4     4;
   4.5   4.5]

but I can't seem to manipulate the reshape function to do this for me

Upvotes: 1

Views: 131

Answers (1)

Lanting
Lanting

Reputation: 3068

edit: the single line version might be a bit complicated, so I've also added one based on a for loop

2 reshapes and a permute should do it (we first split the matrices and store them in 3d), and then stack them. In order to stack them we first need to permute the dimensions (similar to a transpose).

>> reshape(permute(reshape(a,2,2,4),[1 3 2]),8,2)

ans =

    1.0000    1.0000
    1.5000    1.5000
    2.0000    2.0000
    2.5000    2.5000
    3.0000    3.0000
    3.5000    3.5000
    4.0000    4.0000
    4.5000    4.5000

the for loop based version is a bit more straight forward. We create an empty array of the correct size, and then insert each of the 2x2 matrices separately:

b=zeros(8,2);
for i=1:4,
  b((2*i-1):(2*i),:) = a(:,(2*i-1):(2*i));
end

Upvotes: 2

Related Questions