reshape a 2D to 3D matrix

조회 수: 1 (최근 30일)
Yujiao Li
Yujiao Li 2015년 3월 31일
편집: Star Strider 2015년 3월 31일
My data
ID X1 X2
1 1 2
1 5 2
2 2 4
2 4 7
3 2 4
3 4 7
3 5 11
My goal is to have the submatrix based on the ID. The question is when the rows of each submatrix is not the same, how can i get the following result?
Matrix(:,:,1)=
1 1 2
1 5 2
Matrix(:,:,2)=
2 2 4
2 4 7
Matrix(:,:,3)=
3 2 4
3 4 7
3 5 11

답변 (1개)

Star Strider
Star Strider 2015년 3월 31일
You have to use a cell array, but it is relatively easy:
D = {1 1 2
1 5 2
2 2 4
2 4 7
3 2 4
3 4 7
3 5 11};
Matrix = {D(1:2,:) D(3:4,:) D(5:7,:)};
Matrix{:} % Check Result
produces:
ans =
[1] [1] [2]
[1] [5] [2]
ans =
[2] [2] [4]
[2] [4] [7]
ans =
[3] [2] [ 4]
[3] [4] [ 7]
[3] [5] [11]
  댓글 수: 3
Yujiao Li
Yujiao Li 2015년 3월 31일
Thanks a lot. But my goal is to construct a 3D data stucture by loop. so that I can use x(:,:,i) and x(:,:,j) to calculate further. Could you help me on improve my code:
ID.uni=unique(ID); k=length(ID.uni); X=[]; for i=1:k rows_i= D(:,1)==ID.uni(i); % index which rows have the same ID X(:,:,i)=D(rows_i,2:3); end
Thank you so much!
Star Strider
Star Strider 2015년 3월 31일
편집: Star Strider 2015년 3월 31일
My pleasure!
It has to be a cell array, so I would simply do this, taking advantage of the third output of unique, using accumarray as a bin counter, and mat2cell to create the cell array:
D = [1 1 2
1 5 2
2 2 4
2 4 7
3 2 4
3 4 7
3 5 11];
[IDuni,~,ic]=unique(D(:,1));
rows_i = accumarray(ic,1);
X = mat2cell(D, rows_i, 3)
Matrix_1 = X{1} % Display Resultd
Matrix_2 = X{2}
Matrix_3 = X{3}
producing:
X =
[2x3 double]
[2x3 double]
[3x3 double]
Matrix_1 =
1 1 2
1 5 2
Matrix_2 =
2 2 4
2 4 7
Matrix_3 =
3 2 4
3 4 7
3 5 11

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

카테고리

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