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?
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.