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

1 view (last 30 days)
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

Guillaume
Guillaume on 23 Oct 2014
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]);

More Answers (1)

Geoff Hayes
Geoff Hayes on 23 Oct 2014
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
lee
lee on 23 Oct 2014
Edited: lee on 23 Oct 2014
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])
Guillaume
Guillaume on 23 Oct 2014
Edited: Guillaume on 23 Oct 2014
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

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!