Command to reshape matrix diagonally

조회 수: 3 (최근 30일)
fr_sk
fr_sk 2016년 4월 8일
댓글: Andrei Bobrov 2016년 4월 8일
Hi, i'd like to transform
X = 1 100 40
2 107 30
3 90 50
4 120 60
into
Y = 1 100 40 3 90 50
2 107 30 4 120 60
I thought
Y = reshape(X,2,6)
would do the trick but it didn't give me the matrix I was looking for.
Any quick ideas will be appreciated.
Thanks!

채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 4월 8일
편집: Andrei Bobrov 2016년 4월 8일
% X - array with size [5541888 x 7]
% m2 - number of rows in second array, m2 = 1536
[~,n] = size(X);
out = reshape(permute(reshape(X',n,m2,[]),[1 3 2]),[],m2)';
or
[m,n] = size(X);
a = mat2cell(X,m2*ones(m/m2,1),n);
out = [a{:}];
  댓글 수: 2
fr_sk
fr_sk 2016년 4월 8일
This is the perfect solution, it works like charm!!! Thank you so much!
Just so I understand what you did: What does [1 3 2] do in this case? Also why X' instead of X ?
Andrei Bobrov
Andrei Bobrov 2016년 4월 8일
rewrite on separate commands:
[~,n] = size(X);
a = reshape(X',n,m2,[]);
b = permute(a,[1 3 2]);
out = reshape(b,[],m2)';
Please read about MATLAB functions: ' - transpose, reshape, permute.

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

추가 답변 (1개)

Rick Rosson
Rick Rosson 2016년 4월 8일
Y = [ X(1:end/2,:) X(end/2+1:end,:) ];
  댓글 수: 1
fr_sk
fr_sk 2016년 4월 8일
Wow, thanks a lot for the fast response. This works very well for this example. My actual dataset has the dimensions of 5541888 x 7, which I want to stack according to your method to obtain a 1536 X 25256 matrix.
I wanted to apply your idea, but then I realized that I have to enter the code for each column manually. Do you think there is a way to do it for these dimensions?

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

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by