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: [mg70406] Re: how to sum lists of unequal length?
  • From: "Philpp" <piotr at bigpond.net.au>
  • Date: Sun, 15 Oct 2006 00:20:16 -0400 (EDT)
  • References: <egq2th$84h$1@smc.vnet.net>

Arek,

You might want to use one of the following functions:

Clear["sum*"];
sum1[x_List, y_List] :=
    Join[x + Take[y, Length[x]], Take[y, Length[x] - Length[y]]] /;
        Length[y] >= Length[x]
sum1[x_List, y_List] := sum1[y, x]

sum2[x_List, y_List] :=
    PadRight[x, Length[y]] + y /; Length[y] >= Length[x]
sum2[x_List, y_List] := sum2[y, x]

In[1]:=  a = {a1, a2, a3};
         b = {b1, b2, b3, b4, b5};

         sum1[a, b]
         sum1[a, {}]
         sum1[{}, {}]
         sum1[{}, b]
         sum1[b, a]

Out[3]=  {a1 + b1, a2 + b2, a3 + b3, b4, b5}
Out[4]=  {a1, a2, a3}
Out[5]=  {}
Out[6]=  {b1, b2, b3, b4, b5}
Out[7]=  {a1 + b1, a2 + b2, a3 + b3, b4, b5}

In[8]:=  sum2[a, b]
         sum2[a, {}]
         sum2[{}, {}]
         sum2[{}, b]
         sum2[b, a]

Out[8]=  {a1 + b1, a2 + b2, a3 + b3, b4, b5}
Out[9]=  {a1, a2, a3}
Out[10]= {}
Out[11]= {b1, b2, b3, b4, b5}
Out[12]= {a1 + b1, a2 + b2, a3 + b3, b4, b5}


I hope this is what you wanted.

Cheers,

Phil.

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


  • Prev by Date: Re: General--Simple Permutations
  • Next by Date: variable metric method automatic gradient yields Indeterminate
  • Previous by thread: Re: how to sum lists of unequal length?
  • Next by thread: Re: how to sum lists of unequal length?