Transpose a matrix within a matrix

조회 수: 1 (최근 30일)
Alexandra
Alexandra 2014년 7월 5일
편집: Cedric 2014년 7월 5일
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
Cedric
Cedric 2014년 7월 5일
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
Alexandra
Alexandra 2014년 7월 5일
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.
Cedric
Cedric 2014년 7월 5일
편집: Cedric 2014년 7월 5일
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개)

the cyclist
the cyclist 2014년 7월 5일
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

카테고리

Help CenterFile 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