Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2006
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2006

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: how to sum lists of unequal length?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg70403] Re: [mg70352] how to sum lists of unequal length?
  • From: "Adriano Pascoletti" <pascolet at dimi.uniud.it>
  • Date: Sun, 15 Oct 2006 00:20:07 -0400 (EDT)

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.
> 
> Please, help
> 
> Arek
> 

Arek,
a solution which precomputes the lengths:

In[1]:=
listSum[a__List] := With[{len = Max[Length /@ {a}]}, 
    Plus @@ (PadRight[#1, len] & ) /@ {a}]; 

In[2]:=
listSum[Array[a, {2}], Array[b, {6}], Array[c, {4}]]

Out[2]=
{a[1] + b[1] + c[1], a[2] + b[2] + c[2], b[3] + c[3], 
  b[4] + c[4], b[5], b[6]}

A trickier one based on Sow and Reap:

In[3]:=
listSum2[a__List] := 
  Reap[MapIndexed[Sow[#1, Last[#2]] & , {a}, {2}], _, 
    Total[#2] & ][[2]]


In[4]:=
listSum2[Array[a,{2}],Array[b,{6}],Array[c,{4}]]

Out[4]=
{a[1]+b[1]+c[1],a[2]+b[2]+c[2],b[3]+c[3],b[4]+c[4],b[5],b[6]}


Adriano Pascoletti



  • Prev by Date: Re: path for package
  • Next by Date: Re: Is it possible to "pre-evaluate" parts of pure function?
  • Previous by thread: Re: how to sum lists of unequal length?
  • Next by thread: Re: how to sum lists of unequal length?