Reputation: 35
Apologies if something similar has been asked before. It seems like it should be an easy problem on the face of it, but I'm having trouble describing this -- let alone solving it! Let's suppose I have a single 5 x 3 matrix that looks something like this:
A = [50 1 2
75 2 3
20 2 3
10 1 1
90 1 2]
I want to sum the values in the first column wherever there is a pair in the 2nd and 3rd column that is duplicated somewhere else. So, I'm trying to transform A (above) into something like this 3 x 3 matrix B, where:
B = [140 1 2
95 2 3
10 1 1]
Just the values from column 1 get added, and I need them to stay matched to the pair that "caused" them to combine. I guess I should also add that the order of values in columns 2 & 3 does matter in that 3,4 counts as a different pair than 4,3. (Of course my actual data include values in columns 2 & 3 that range well into the 100s, so writing an if statement for each possible combination isn't really a possibility...)
Any suggestions for this would be much appreciated! I was studying the documentation on 'find' and stumbled across something called 'ismember' -- do I need to be using some application of that?
Upvotes: 3
Views: 62
Reputation: 112679
The usual unique
- accumarray
couple is suited for the job:
[u, ~, v] = unique(A(:,2:end), 'rows', 'stable');
B = [accumarray(v, A(:,1)) u];
Upvotes: 3