MATLAB: Summing values in one column when a condition has been applied to 2 other columns

columnsmatrixsumming

I have a matrix that is 2074 x 4. I have simplified this to A (4 x 4)
A = [1 4 5 6,
1 5 5 8,
2 3 9 9,
3 4 5 7];
I want to sum the values in column 4 when values in column 1 are the same as one another AND the values in column 3 are the same as one another (but not necessarily the same as those in column 1). So in the case of A I would sum 6 + 8 to give 14.
I can do this for one column using S = accumarray(A(:,1), A(:,4), [], @sum) but not when two columns have identical values.

Best Answer

The trick is to use unique with the 'rows' option, and get its third (index) output:
>> [~,~,idx] = unique(A(:,[1,3]),'rows');
>> S = accumarray(idx, A(:,4), [], @sum)
S =
14
9
7