How to group arrays in matrix

6 次查看(过去 30 天)
Amy Xu
Amy Xu 2017-4-10
评论: Stephen23 2017-4-10
Matrix A as follows:
A = [
1
1
1
2
2
4
4
7
8
8
9
];
I want to group by matrix A as follows:
B = [
1 3
2 2
4 2
7 1
8 2
9 1
];
  1 个评论
Stephen23
Stephen23 2017-4-10
The old fashioned way:
>> U = unique(A);
>> [U,hist(A,U).']
ans =
1 3
2 2
4 2
7 1
8 2
9 1

请先登录,再进行评论。

回答(2 个)

Thorsten
Thorsten 2017-4-10
编辑:Thorsten 2017-4-10
If the second row is the number of occurrences then you can use
[a, ~, c] = unique(A);
B = [a, accumarray(c, 1)];

Guillaume
Guillaume 2017-4-10
A = [1 1 1 2 2 4 4 7 8 8 9]'
B = unique(A);
B = [B, histcounts(A, [B; Inf]).']

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by