Re: how to sum lists of unequal length?
- To: mathgroup at smc.vnet.net
- Subject: [mg70421] Re: how to sum lists of unequal length?
- From: Peter Pein <petsie at dordos.net>
- Date: Mon, 16 Oct 2006 02:34:15 -0400 (EDT)
- References: <egq2th$84h$1@smc.vnet.net>
Arkadiusz.Majka at gmail.com schrieb: > 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. > > Please, help > > Arek > Hi Arek, you don't need to have an idea, because Mathematica can easily estimate the maximal length of the lists to sum: In[1]:= (* generate 3 Lists of length 3, 7 and 5 resp. *) myLists=Inner[Map[#1,Range[#2]]&,{a,b,c},{3,7,5},List] Out[1]= {{a[1],a[2],a[3]}, {b[1],b[2],b[3],b[4],b[5],b[6],b[7]}, {c[1],c[2],c[3],c[4],c[5]}} and this determines the maximal length, pads an appropriate number of zeros to the shorter lists and adds them: In[2]:= Total[PadRight[#,Max[Length/@myLists]]&/@myLists] Out[2]= {a[1]+b[1]+c[1],a[2]+b[2]+c[2],a[3]+b[3]+c[3],b[4]+c[4],b[5]+c[5],b[6],b[7]} Easy, isn't it? :-) Greetings, Peter