16

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?

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
novice
  • 2,325
  • 1
  • 24
  • 30
  • 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 01 '13 at 01:21

3 Answers3

17

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} *)
rm -rf
  • 88,781
  • 21
  • 293
  • 472
15
Plus @@ PadRight[{{1, 2, 3}, {a, b}, {x}}]

I think it can also work.

Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453
Life
  • 660
  • 3
  • 12
3

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}]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371