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.

Given lists of unequal lengths, I want to add them together element-wise, treating missing elements as zero. For example, {1, 2, 3} + {a, b} + {x} should give {1 + a + x, 2 + b, 3}.

How do I write a function to do this?

share|improve this question
    
for two lists, fadd[a_, b_] := (PadRight[a, Length@b] + b) /; Length[b] > Length[a]; fadd[a_, b_] := (PadRight[b, Length@a] + a) /; Length[a] > Length[b] should work. This can be modified for more than two lists. –  acl Apr 1 '13 at 1:21
add comment

4 Answers

up vote 9 down vote accepted
Plus @@ PadRight[{{1, 2, 3}, {a, b}, {x}}]

I think it can also work.

share|improve this answer
3  
Neat and simple,I can define fadd=Plus @@ PadRight[{##}]&; –  novice Apr 1 '13 at 6:40
add comment

You can simply do a ragged transpose and then add, which saves you the trouble of having to pad the lists:

Total /@ Flatten[{{1, 2, 3}, {a, b}, {x}}, {2}]
(* {1 + a + x, 2 + b, 3} *)
share|improve this answer
    
I notice you've exceeded 100 silver badges. Wow! :-) –  Mr.Wizard Apr 1 '13 at 3:51
    
Thanks, I've had it for a while now :) Now I need to catch the slow train to a list-manipulation gold to join you (you're just mere days away). –  rm -rf Apr 1 '13 at 19:14
    
This works, too: Total[Flatten[{{1, 2, 3}, {a, b}, {x}}, {2}], {2}] –  J. M. Apr 11 '13 at 12:45
add comment

Using raggedMapThread from this answer we could write:

raggedMapThread[Plus, {{1, 2, 3}, {a, b}, {x}}]
{1 + a + x, 2 + b, 3}

This is can also be easily extended to additional dimensions:

raggedMapThread[Plus, {{{1}, {2, 3}}, {{a, b}, {q}}, {{x}}}, 2]
{{1 + a + x, b}, {2 + q, 3}}

Again for reference the code is:

raggedMapThread[f_, expr_, level_Integer: 1] := 
 Apply[f, Flatten[expr, List /@ Range[2, level + 1]], {level}]
share|improve this answer
add comment

answer moved from: adding vectors of unequal length

Not so fast but good to know.

inp = {{1, 2, 3}, {a, b}, {x}}

ClearAll[add];
add[_] = 0;
add[a_, {x_, y_}] := add[y] += a
MapIndexed[add, inp, {2}];

add /@ Range[Max[Length /@ inp]]
{1 + a + x, 2 + b, 3}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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