Section a 2d matrix and put the sections into a 3d matrix
1 view (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
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
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).
See Also
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!