I was wondering if there is an automatic way to do this kind of matrix operation.
For example, for a given matrix
list = {{1, 3T}, {3, 8T}, {2, 2T}, {1, 5T}, {4, 6T}};
I want the result to be like this as shown below after the operation.
result = {{1 ,8T}, {2, 2T}, {3, 8T}, {4, 6T}}
The operation will add the terms in the second column if they have the same number in the first column for all the rows. i.e. for the first row, the second term is calculated as 3T
plus 5T
,which is the term in list[[4,2]]
.
{#[[1, 1]], Total[#[[All, 2]]]} & /@ GatherBy[list, First] // Sort
? $\endgroup$ – kglr Aug 11 '14 at 11:30SortBy[Last@Reap[Sow @@@ (Reverse /@ list), _, {#1, Total@#2} &], First]
...omitSortBy
if order not important $\endgroup$ – ubpdqn Aug 11 '14 at 11:42