Reputation: 3898
I have a long nx3
matrix. For eg, I take a 9x3
matrix
A =
8 9 8
9 2 9
2 9 6
9 9 1
6 5 8
1 8 9
3 2 7
5 4 7
9 9 7
Now I want it reshaped, (taking successive 3x3
sub-matrix to the next dimension) such that,
out(:,:,1) =
8 9 8
9 2 9
2 9 6
out(:,:,2)
9 9 1
6 5 8
1 8 9
out(:,:,3)
3 2 7
5 4 7
9 9 7
I could do this with loops but I wanted to know how to vectorize this process..
Can i do it with reshape
and permute
alone?
Upvotes: 2
Views: 100
Reputation: 25232
Yes, you can use permute
and reshape
:
A = [...
8 9 8
9 2 9
2 9 6
9 9 1
6 5 8
1 8 9
3 2 7
5 4 7
9 9 7
3 2 7
5 4 7
9 9 7]
n = size(A,2);
B = permute( reshape(A.',n,n,[]), [2 1 3]) %'
%// or as suggested by Divakar
%// B = permute( reshape(A,n,n,[]), [1 3 2])
out(:,:,1) =
8 9 8
9 2 9
2 9 6
out(:,:,2) =
9 9 1
6 5 8
1 8 9
out(:,:,3) =
3 2 7
5 4 7
9 9 7
out(:,:,4) =
3 2 7
5 4 7
9 9 7
Upvotes: 4
Reputation: 221714
This could be one approach -
N = 3
out = permute(reshape(A,N,size(A,1)/N,[]),[1 3 2])
This one has the advantage of avoiding the transpose as used in the other answer by @thewaywewalk.
Sample run -
A =
8 9 8
9 2 9
2 9 6
9 9 1
6 5 8
1 8 9
3 2 7
5 4 7
9 9 7
out(:,:,1) =
8 9 8
9 2 9
2 9 6
out(:,:,2) =
9 9 1
6 5 8
1 8 9
out(:,:,3) =
3 2 7
5 4 7
9 9 7
Upvotes: 3