0
$\begingroup$

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]].

$\endgroup$
  • $\begingroup$ Thanks for your help, Oska. Much appreciated! $\endgroup$ – user11726 Aug 11 '14 at 11:11
  • 1
    $\begingroup$ {#[[1, 1]], Total[#[[All, 2]]]} & /@ GatherBy[list, First] // Sort? $\endgroup$ – kglr Aug 11 '14 at 11:30
  • $\begingroup$ Just another way: SortBy[Last@Reap[Sow @@@ (Reverse /@ list), _, {#1, Total@#2} &], First]...omit SortBy if order not important $\endgroup$ – ubpdqn Aug 11 '14 at 11:42
  • $\begingroup$ Nice to see so many contributions, and thanks for the heads up! $\endgroup$ – user11726 Aug 13 '14 at 4:47

Browse other questions tagged or ask your own question.