reshape a 2D to 3D matrix

1 次查看(过去 30 天)
Yujiao Li
Yujiao Li 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