16
$\begingroup$

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?

$\endgroup$
1
  • $\begingroup$ 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. $\endgroup$
    – acl
    Commented Apr 1, 2013 at 1:21

3 Answers 3

15
$\begingroup$
Plus @@ PadRight[{{1, 2, 3}, {a, b}, {x}}]

I think it can also work.

$\endgroup$
1
  • 4
    $\begingroup$ Neat and simple,I can define fadd=Plus @@ PadRight[{##}]&; $\endgroup$
    – novice
    Commented Apr 1, 2013 at 6:40
17
$\begingroup$

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} *)
$\endgroup$
3
  • $\begingroup$ I notice you've exceeded 100 silver badges. Wow! :-) $\endgroup$
    – Mr.Wizard
    Commented Apr 1, 2013 at 3:51
  • $\begingroup$ 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). $\endgroup$
    – rm -rf
    Commented Apr 1, 2013 at 19:14
  • $\begingroup$ This works, too: Total[Flatten[{{1, 2, 3}, {a, b}, {x}}, {2}], {2}] $\endgroup$ Commented Apr 11, 2013 at 12:45
3
$\begingroup$

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}]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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