Re: Summing over like elements

• To: mathgroup at smc.vnet.net
• Subject: [mg13876] Re: Summing over like elements
• From: buttgereit at netcologne.de (Peter Buttgereit)
• Date: Wed, 2 Sep 1998 01:31:09 -0400
• Organization: Dipl.-Sportl. Peter Buttgereit
• References: <6sdb8i\$peq@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```[This followup was posted to comp.soft-sys.math.mathematica and a copy
was sent to the cited author.]

In article <6sdb8i\$peq at smc.vnet.net>, qmak at pipeline.com says...
> I have a 2 column array.  Column 1 has some values, many of which are
> repeated.  Column 2 has probabilities of these values.
>
> I would like to sum the probabilities for each unique element in column
> 1. For example:
>
> {{1, .5} , {2, .2} , {1, .1}}  should give me:
>
> {{1, .6} , {2, .2}}
>
>
> I'm sure I can do this with a "Do" loop -- however it seems that in
> general "Do's" are pretty innefficient.
>
> Does anyone have any suggestions?
>
>                 Mitch
>
>
Hi Mitch,

tmp=Split[
Sort[ yourList, (#1[[1]]<#2[[1]])& ],
SameQ[ #1[[1]], #2[[1]] ]&
]                                               (*1*)

sumP[a_List]:={#[[1,1]],Plus@@#[[2]]}&@Transpose[a] (*2*)

sumP/@tmp                                           (*3*)

(1) will produce sublists of identical elements in the first position of
{{{i,pi1},...,{i,pin}},{{j,pj1},...,{j,pjm}},...}. (2) will take one of
these sublists, extract the first element, sum over  p and return {i,
sum[pin]}.
In (3) you map sumP on all the sublists of tmp, produced in (1),
returning the desired output {{i,sum[pin]},{j,sum[pjm]}...} --- let's
see what the other guys come up with...(probably something faster;  at
least my version is without "Do" <g>). So long,
cheers,
Peter

```

• Prev by Date: Re: Summing over like elements
• Next by Date: Re: UNEXPECTED END OF FILE !!!!!!
• Previous by thread: Re: Summing over like elements
• Next by thread: Re: Summing over like elements