Re: how to sum lists of unequal length?

*To*: mathgroup at smc.vnet.net*Subject*: [mg70393] Re: how to sum lists of unequal length?*From*: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>*Date*: Sun, 15 Oct 2006 00:19:09 -0400 (EDT)*Organization*: The Open University, Milton Keynes, UK*References*: <egq2th$84h$1@smc.vnet.net>

Arkadiusz.Majka at gmail.com wrote: > Hi all, > > I have lists of unknown and unequal lengths. I want to sum them, e.g > > {a1,a2,a3}+{b1,b2,b3,b4,b5} and obtain result > {a1+b1,a2+b2,a3+b3,b4,b5}. Simply filling by zeros of the shorter list > is impossible because I have no idea how many zeros I have to pad. The following function takes as argument a list of all the lists of unequal length that one wants to sum, pads the shorter list with zeros, then computes the sum: In[1]:= mySum[expr_] := Module[{n}, n = Max[Length /@ expr]; Total[(PadRight[#1, n] & ) /@ expr]] In[2]:= lst1 = {a1, a2, a3}; lst2 = {b1, b2, b3, b4, b5}; expr = {lst1, lst2}; mySum[expr] Out[5]= {a1 + b1, a2 + b2, a3 + b3, b4, b5} Regards, Jean-Marc