reshape a 2D to 3D matrix
4 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Star Strider
on 31 Mar 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 Comments
Star Strider
on 31 Mar 2015
Edited: Star Strider
on 31 Mar 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
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!