How can I create a sub-matrix from a matrix with repeated values in a column?

5 次查看(过去 30 天)
I'm having troubles when I try to create a sub-matrix from a matrix with a column with repeated values.
For example, let consider the matrix A:
A = [1 6 13 34 26 27;
1 7 14 35 25 28;
1 8 15 36 24 29;
2 9 16 37 23 30;
2 10 17 38 22 31;
3 11 3 18 21 32; ]
I would like to obtain, not for a specific matrix A like in this example but for any given A, the sub-matrix B, C and D bellow:
B = [ 1 6 13 34 26 27;
1 7 14 35 25 28;
1 8 15 36 24 29; ]
C = [2 9 16 37 23 30;
2 10 17 38 22 31; ]
D = [3 11 3 18 21 32; ]
Thank you very much for your help.
  2 个评论
Mario Malic
Mario Malic 2020-5-6
In addition to Emmanuel's comment which is useful for creating specific matrices, you either need to write the for loop to find elements with repeated values and figure out how to get their indices and just create sub-matrices out of those.
The other way is the diff function, which, in your case is
diff(A(1:end,1))
From here you need to figure things out.

请先登录,再进行评论。

采纳的回答

Star Strider
Star Strider 2020-5-6
Use the accumarray function:
[Au,~,ic] = unique(A(:,1));
Outc = accumarray(ic, (1:size(A,1))', [], @(x){A(x,:)});
producing:
B = Outc{1}
C = Outc{2}
D = Outc{3}
B =
1 6 13 34 26 27
1 7 14 35 25 28
1 8 15 36 24 29
C =
2 9 16 37 23 30
2 10 17 38 22 31
D =
3 11 3 18 21 32
The unique call (although uniquetol would be more generally applicable), is not strictly necessary here because ‘A(:,1)’ are consecutive integers. However since that may not always be the situation, I included it to make the code more robust.

更多回答(1 个)

Emmanuel Olivar
Emmanuel Olivar 2020-5-6
You can use concatenation to make this action. For example:
If I have Matrix A:
A = [1 6 13 34 26 27;
1 7 14 35 25 28;
1 8 15 36 24 29;
2 9 16 37 23 30;
2 10 17 38 22 31;
3 11 3 18 21 32;]
If you need Matrix B, you use the next command:
B = A([1,2,3],:)
I use the vector [1,2,3] to get rows 1,2 and 3 and : to get all column values.
Now, if I need the Matrix C, I use the command:
C = A([4,5],:)
Again, I use the vector [4,5] to get rows 4 and 5 and : to get all column values.
Finally, if I need the Matrix D, I use the command:
D = A(6,:) % or D = A(end,:)
Show what happend when you use the next command:
E = A([1,3,5],[2 3])
You can show a better explanation of this topic in:
  1 个评论
Everton
Everton 2020-5-6
Thank you very much for your help! Maybe I wasnt clear when I asked for help. Actualy I needed to identify (automatically) the repeated values in the first column and create a sub-matrix for each "group of lines" corresponding to those values. But I aprecciate your help anyway.

请先登录,再进行评论。

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by