reshape a 2D to 3D matrix

1 Ansicht (letzte 30 Tage)
Yujiao Li
Yujiao Li am 31 Mär. 2015
Bearbeitet: Star Strider am 31 Mär. 2015
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

Antworten (1)

Star Strider
Star Strider am 31 Mär. 2015
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 Kommentare
Yujiao Li
Yujiao Li am 31 Mär. 2015
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 am 31 Mär. 2015
Bearbeitet: Star Strider am 31 Mär. 2015
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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by