0
votes

I have some problems using reshape. I want to reshape a 4-dimensional matrix, and the fourth dimension has to become a column.

so if I have:

A(:,:,1,1) =

 1     4
 2     5

A(:,:,2,1) =

 2     5
 3     6

A(:,:,1,2) =

10    14
12    15

A(:,:,2,2) =

12    15
13    16

My reshape should be:

Columns 1 through 5

 1     4     2     5     2
10    14    12    15    12

Columns 6 through 8

 5     3     6
15    13    16
2

2 Answers

0
votes

This should work:

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

To understand this, you can go step by step. First do the following:

reshape(A,[2 8])

ans =

 1     2     2     3    10    12    12    13
 4     5     5     6    14    15    15    16

You observe that the columns of the reshaped matrix are taken by sliding across the second dimension in the original matrix. After second dimension is over, you slide over to third dimension and the re-iterate over second dimension (here first dimension is rows, second is column, so on...).

What you want to do is, iterate over 4th dimension (as if its a second dimension). You also want (4,14) after (1,10). You can see that corresponding elements vary across second dimension (but reshape is going to slide over third dimension, no matter what. So swap 2nd and 3rd dimensions).

Finally, you get, reshape(permute(A,[1 4 2 3]),[2 8]).

I have always had a hard time explaining permute to somebody. I hope I didn't confuse you more.

0
votes

You're going to have to do a permutation first to put the dimensions in the appropriate order. Try this:

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

or break it up into two separate permutations, one to switch dimensions 1 and 2 in the original array, then reshape to 8x2, then take the transpose:

reshape(permute(A,[2,1,3,4]),[8,2])'