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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by