Sum rows that have duplicate values in 2 other rows
Show older comments
I have a 345,505 x 13 matrix of doubles. I need to sum the columns 2 and 4-13 of any rows that have the same value in column 1, and the same value in column 3, so that they combine into one row. I've already sorted them by columns 1 and 3.
Example with a 4x7 matrix:
oldMatrix
1 3 1 0 4 3
1 9 1 2 2 3
2 3 1 3 2 1
3 4 5 0 1 2
Since the first two rows match, they need to combine to one row:
newMatrix
1 12 1 2 6 9
2 3 1 3 2 1
3 4 5 0 1 2
Thanks for your help!
2 Comments
Image Analyst
on 26 Nov 2017
How do you get 9 in the last column of row #1? Why is it not 3+3=6? Is it possible that there may be any number of such rows, or is it always just 1 row or 2 rows?
Andrew Marku
on 26 Nov 2017
Accepted Answer
More Answers (1)
Jos (10584)
on 26 Nov 2017
a = [1 3 1 0 4 3 ; 1 9 1 2 2 3 ; 2 3 1 3 2 1 ; 3 4 5 0 1 2]
[ua,~,j] = unique(a(:,[1 3]),'rows','stable')
c = arrayfun(@(k) sum(a(k==j,:),1),1:max(j),'un',0)
b = cat(1,c{:})
b(:,[1 3]) = ua
2 Comments
Andrew Marku
on 26 Nov 2017
Jos (10584)
on 27 Nov 2017
Look at the documentation for each function to gain some understanding. The arrayfun code is a little bit tricky: it sums up each column for those rows that have identical rows when you look only at column 1 and 3 (so, yes!).
Categories
Find more on Introduction to Installation and Licensing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!