Section a 2d matrix and put the sections into a 3d matrix

Hi,
I have a question, if I have a matrix, lets say a 3x12 matrix:
a=
1 1 1
1 1 1
1 1 1
1 1 1
2 2 2
2 2 2
2 2 2
2 2 2
3 3 3
3 3 3
3 3 3
3 3 3
is there a method other than for looping to section this matrix and place the elements in a 3d matrix such, that it has a structure of (without changing the position of the 1, 2, 3 elements):
b(:,:,1) =
1 1 1
1 1 1
1 1 1
1 1 1
b(:,:,2) =
2 2 2
2 2 2
2 2 2
2 2 2
b(:,:,3) =
3 3 3
3 3 3
3 3 3
3 3 3
Is there a method doing this without using for looping?

 Accepted Answer

Just repeating my comment as an answer, in case you want to credit it:
b = permute(reshape(a',[3 3 3]), [2 1 3]);
if starting with a0:
b = permute(reshape(a0', [3 3 3], [3 2 1]);

2 Comments

Thank you very much! I do like to credit it!

Sign in to comment.

More Answers (1)

You can use the reshape function to produce the desired result without looping. Since each of the three dimensions corresponds to a 4x3 matrix, then we do
b = reshape(a',[4 3 3]);
which produces the above result. Note that reshape returns a result, b, whose elements are taken column-wise from the input matrix a. Since we want the "top" 4x3 sub matrix of a to be copied as b(:,:,1), then we must transpose a (given by the apostrophe).

3 Comments

ohh! thank you very much for the reply, I thought about reshaping, but not this one :).
This is a very nice solution! But I think I might not explained my problem correctly, the problem with this solution is, that the positions of the '1's have shifted during the reshaping, so the (:,:,1) of the new matrix and the 'top' 4x3 sub matrix of the old matrix are actually not the same anymore, and because in a real situation, the positions of the '1's are actually occupied with different values, so this shifting is bad...
sorry for the confusion, so the real problem should look like this,
a= [ 1.1 2.1 3.1
4.1 5.1 6.1
7.1 8.1 9.1
1.2 2.2 3.2
4.2 5.2 6.2
7.2 8.2 9.2
1.3 2.3 3.3
4.3 5.3 6.3
7.3 8.3 9.3 ],
and
b should be
b(:,:,1)=[ 1.1 2.1 3.1
4.1 5.1 6.1
7.1 8.1 9.1 ]
b(:,:,2)=[ 1.2 2.2 3.2
4.2 5.2 6.2
7.2 8.2 9.2 ]
b(:,:,3)= [ 1.3 2.3 3.3
4.3 5.3 6.3
7.3 8.3 9.3 ],
too further clearify the problem, the matrix "a" is actually a matrix reshaped from other matrix, which represents actuarally solutions of an ODE system:
a0=[ 1.1 1.2 1.3 2.1 2.2 2.3 3.1 3.2 3.3
4.1 4.2 4.3 5.1 5.2 5.3 6.1 6.2 6.3
7.1 7.2 7.3 8.1 8.2 8.3 9.1 9.2 9.3 ],
and a=reshape(a0,[9 ,3])
You need to permute (== transpose but for 3d matrices) the output of reshape:
b = permute(reshape(a',[3 3 3]), [2 1 3]);
following up on your edit to your comment:
if starting with a0:
b = permute(reshape(a0', [3 3 3], [3 2 1]);

Sign in to comment.

Categories

Asked:

lee
on 23 Oct 2014

Commented:

on 23 Oct 2014

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!