Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I am interested in summing elements in a list or sublist that are similar.

I want the sublists of my second elements to be added cumulatively only if their first elements are the same.

This is my list: {{3, 1}, {5, 1}, {5, 2}, {3, 3}}.

This is my desired result: {{1,1},{1,3},{4,3}}.

share|improve this question

closed as unclear what you're asking by Artes, rasher, m_goldberg, Kuba, ubpdqn Apr 25 at 11:21

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

    
I have made edits, take a look at it again. –  Crisp Apr 25 at 7:26
    
Your example list isn't actually a list. Please correct. –  Sjoerd C. de Vries Apr 25 at 7:33
    
ok {3, 1} + {5, 1}, since they have no similar first elements, we let the second elements remain {1,1}. and then {3,1}+{5,2}, since the first element is not common we have 1, then we have {5,1}+{5,2} since the first element is common, we have 3, now we have {1,3}, now last we have {3,1}+{3,3}=4 and {5,3}+{3,3}=3. now we have {4,3} –  Crisp Apr 25 at 7:46
    
you just add the second elements of each sublist recursively only if the first element matches. –  Crisp Apr 25 at 7:46
1  
{3, 1} + {5, 1} -> {1,1} and {3,1} + {5,2} -> 1 how is this consistent? {5,1}+{5,2}-> {1,3} where is that 1 from? Also... {5,3}+{3,3} have I missed something?, like {5,3}? I certainly need a starting coffee but I can bet it will be still unclear to me :) –  Kuba Apr 25 at 8:00

1 Answer 1

up vote 1 down vote accepted

Look this

lst={{3,1},{5,1},{5,2},{3,3}};
firstElem=DeleteDuplicates@lst[[All,1]];
firstIndex=(Flatten[Position[firstElem,#[[1]]]][[1]])&/@lst;
res=ConstantArray[0,Length[firstElem]];
Table[res[[firstIndex[[i]]]]+=lst[[i,2]]; res,{i,1,Length[lst]}]

(*{{1, 0}, {1, 1}, {1, 3}, {4, 3}}*)
share|improve this answer
    
I can do with this, thank you! –  Crisp Apr 25 at 8:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.