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.

This question already has an answer here:

If I have hundreds of vectors of unequal length that I need to sum, what is the cleanest way to do so?

So, if I have as input

inp={{a,b,c,d},{e,f,g},{h}}

I want the answer

{a+e+h,b+f,c+g,d}

I can see how to do this by finding the length of the longest element and then using PadRight[] to make the others match, like so

Total[Map[PadRight[#, Max[Map[Length[#] &, inp]]] &, inp]]

but this feels inelegant. Is there a better way?

share|improve this question

marked as duplicate by Simon Woods, Kuba, Artes, belisarius, Michael E2 Mar 25 at 14:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Your method is exactly what came to mind (before I saw yours). Okay, call me inelegant.. –  Daniel Lichtblau Mar 25 at 14:02
    
@Simon Woods the Ragged Transpose solution in the other thread is exactly what I had in mind. –  Michael Stern Mar 25 at 14:11
add comment

2 Answers 2

up vote 3 down vote accepted

You can use Flatten to transpose the ragged array, then Total:

Total[Flatten[inp, {{2}, {1}}], {2}]
(* {a + e + h, b + f, c + g, d} *)
share|improve this answer
add comment

I'm not sure about elegant but...

Reap[Nest[(Sow[Total[Map[First,#]]];Map[Rest[#]/.{}:>Sequence[]&,#])&,inp,4]][[2,1]]

Loosing the hard-coded 4...

Reap[NestWhile[(Sow[Total[Map[First,#]]];Map[Rest[#]/.{}:>Sequence[]&,#])&,inp,Length[#]>0&]][[2,1]]
share|improve this answer
    
Is there a specific way of moving an answer or do I just repost it there? –  Ymareth Mar 25 at 14:15
    
thanks very much :) –  Ymareth Mar 25 at 14:17
add comment

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