Removing of duplicates from first column and summing of elements in second column

3 次查看(过去 30 天)
Dear All,
I need your help as I am not sure how to solve this problem. Namely, from a matrix with N rows and 2 columns, for example:
X =
1 2
2 3
3 4
4 1
4 3
4 2
5 5
6 8
6 1
I want to get new matrix where in the first column will be shown only unique values, and in the second column (in those rows where were duplicates in the first column) will be shown sum of values of second column.
Result:
Y =
1 2
2 3
3 4
4 6
5 5
6 9
I hope I was clear enough.
Thank you in advance.

采纳的回答

Star Strider
Star Strider 2017-12-31
This works:
[Xu1,~,Ic2] = unique(X(:,1), 'stable');
Tally = accumarray(Ic2, X(:,2));
Y = [Xu1 Tally]
Y =
1 2
2 3
3 4
4 6
5 5
6 9

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by