MathGroup Archive 1998

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

Search the Archive

Re: Summing over like elements

  • To: mathgroup at smc.vnet.net
  • Subject: [mg13875] Re: Summing over like elements
  • From: lawry at maths.ox.ac.uk (James Lawry)
  • Date: Wed, 2 Sep 1998 01:31:08 -0400
  • Organization: Oxford Centre for Industrial & Applied Mathematics
  • References: <6sdb8i$peq@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Mitchell Kaplan <qmak at pipeline.com> wrote:
>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?

Here is one way to do it:

f[list_] := 
  Map[{#, Plus @@ Cases[list, {#, a_} -> a]}&,
Union[Transpose[list][[1]]]]

Here's another:

g[list_] := 
  Sort[list, (#1[[1]] <= #2[[1]])&] //. {x___, {a_, b_}, {a_, c_}, 
        y___} -> {x, {a, b+c}, y}

The first way is much faster.

James Lawry.


  • Prev by Date: Re: MacOS vs. Windows PC for Mathematica?
  • Next by Date: WHere can I get good mathematica notebooks in the web?
  • Previous by thread: Re: Summing over like elements
  • Next by thread: Re: Summing over like elements