Rearranging matrices

조회 수: 4 (최근 30일)
Donald
Donald 2011년 5월 5일
Hi! I am working with a 168x6 matrix that is actually just 28 monthly 6x6 matrices stacked on top of each other. To get the data in a way that is easier for me to work with, I would like to rearrange the matrices so that each 6x6 matrix is placed side by side in a row rather than a column. A simple transpose does not work because the data are in one large matrix and the months are by no means separated. Any recommendations? Thanks!
  댓글 수: 3
Andrei Bobrov
Andrei Bobrov 2011년 5월 5일
as suggested by Sean de
data_new = permute(reshape(data,[6,28,6]),[1 3 2])
Donald
Donald 2011년 5월 5일
I'm pretty new to MATLAB, but I'll check that out. Thanks!

댓글을 달려면 로그인하십시오.

답변 (3개)

Andrei Bobrov
Andrei Bobrov 2011년 5월 5일
more variant
data_new = reshape(permute(reshape(data,[6,28,6]),[1 3 2]),6,[]);

Teja Muppirala
Teja Muppirala 2011년 5월 5일
If your original matrix is called "data"
data_new = zeros(6,168);
for n = 0:(168/6)-1
data_new(:,6*n + (1:6)) = data(6*n + (1:6),:);
end
  댓글 수: 2
Donald
Donald 2011년 5월 5일
thanks!
Teja Muppirala
Teja Muppirala 2011년 5월 5일
What I wrote is the most obvious, simple solution for this problem. But if you need to do this calculation hundreds of thousands of times, or repeatedly on very large datasets (say, 6000000x6), I would actually recommend using andrei's solution because it is actually significantly faster.

댓글을 달려면 로그인하십시오.


Matt Fig
Matt Fig 2011년 5월 5일
I agree with Sean de that indexing into your arrays would be easier if they were stacked in the third dimension.
B = permute(reshape(permute(A,[2 1 3]),6,6,28),[2,1,3]);
Now your first array is:
B(:,:,1)
and the second is:
B(:,:,2)
etc.
Also, you might consider cell arrays:
C = permute(reshape(permute(A,[2 1 3]),6,6,28),[2,1,3]);
C = mat2cell(B,6,6,ones(1,28));
Now your first array is:
C{1}
and your second array is:
C{2}
etc. This makes indexing (getting at a certain array) a lot easier!
If you are unfamiliar with cell arrays, you get to the 3rd row of the 5th array like this:
C{5}(3,:)
  댓글 수: 1
Matt Fig
Matt Fig 2011년 5월 5일
Mental gymnastics this morning...

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by