Transpose a matrix within a matrix
9 views (last 30 days)
Show older comments
I have a matrix that has X rows and 9 columns.
Each row is actually a 3x3 matrix.
I want to transpose all of those 3x3 matrixes. How can I do that?
1 Comment
Cedric
on 5 Jul 2014
Could you give an example with 2 rows, and show how you go from there to two 3 by 3 arrays?
Accepted Answer
Cedric
on 5 Jul 2014
Edited: Cedric
on 5 Jul 2014
Assuming that you obtain a 3x3 matrix from the k-th row of data with
Ak = reshape( data(k,:), 3, 3 ) ;
you can transpose all matrices in data as follows
data_t = data(:,[1 4 7 2 5 8 3 6 9]) ;
4 Comments
Cedric
on 5 Jul 2014
Edited: Cedric
on 5 Jul 2014
I can explain it actually. We need to permute columns of M so the new, permuted M (or M_t in my example) corresponds to the transpose of matrices defined by the original M. Yet, we don't know in which order we have to perform this permutation, so let's find that out..
We start by defining a special row of M whose elements are column numbers:
>> r = 1 : 9
r =
1 2 3 4 5 6 7 8 9
Now we build a matrix out of it to see where these elements end up
>> reshape( r, 3, 3 )
ans =
1 4 7
2 5 8
3 6 9
(which makes sens as MATLAB stores arrays in a column-major fashion). If we transpose this matrix, these elements will end up in the following position
>> reshape( r, 3, 3 ).'
ans =
1 2 3
4 5 6
7 8 9
So now we express this array as a row vector..
>> reshape( reshape( r, 3, 3 ).', 1, [] )
ans =
1 4 7 2 5 8 3 6 9
which provides the order of columns of the original matrix in the new matrix. It shows for example that elements of column 4 of the original M have to be moved to column 2 of the new M (or M_t), for the new M to correspond the the transpose of the original M.
This order is the same for all rows and it won't vary (unless you are dealing with larger matrices), so we can hard code it in the expression for permuting the original M:
M_t = M(:,[1 4 7 2 5 8 3 6 9]) ;
More Answers (1)
the cyclist
on 5 Jul 2014
I am not 100% confident that I understand what you are trying to do, but is this close?
x = rand(6,9)
[m,n] = size(x);
for i = 2:3:(m-1)
for j = 2:3:(n-1)
x(i-1:i+1,j-1:j+1) = x(i-1:i+1,j-1:j+1)';
end
end
0 Comments
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!