Transpose a matrix within a matrix

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 个评论

Could you give an example with 2 rows, and show how you go from there to two 3 by 3 arrays?

请先登录,再进行评论。

 采纳的回答

Cedric
Cedric 2014-7-5
编辑:Cedric 2014-7-5
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 个评论

Thanks.
This is how I end up doing it:
for i=1:size(M,1)
M(i,:) = reshape(reshape(M(i,:), 3, 3)', 1, 9 );
end
Your loop does exactly what my answer
M_t = M(:,[1 4 7 2 5 8 3 6 9]) ;
does in one shot. You should profile both and compare their performance.
Yes, I know. But your answer is bit harder to explain/understand... at least for me.
In terns of performance, I put both in a loop of 100.000. The matrix is 33x9.
Your code: 0.11 seconds
My code: 9.01 seconds
There's a HUGE difference so maybe I'll change it.
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]) ;

请先登录,再进行评论。

更多回答(1 个)

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

类别

帮助中心File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by