MathGroup Archive 2004

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

Search the Archive

Re: Conditonal sum

  • To: mathgroup at smc.vnet.net
  • Subject: [mg50267] Re: [mg50263] Conditonal sum
  • From: "Owen, HL (Hywel)" <H.L.Owen at dl.ac.uk>
  • Date: Tue, 24 Aug 2004 06:22:01 -0400 (EDT)
  • Sender: owner-wri-mathgroup at wolfram.com

The way to think about this is to separate the If[] selection from the
summing.

For example, to select only positive values on a mylist defined as e.g.:

mylist={-1,2,-2,4,1}

we would use:

If[#>0,#,{}]&/@mylist

This leaves a messy list, so we Flatten it to get rid of the empty sets:

Flatten[If[# > 0, #, {}] & /@ mylist]

The sum is then generated by applying Plus[] to this expression:

Plus @@ Flatten[If[# > 0, #, {}] & /@ mylist]

Cheers,

Hywel

> -----Original Message-----
> From: Christopher Grinde [mailto:christopher.grinde at hive.no]
To: mathgroup at smc.vnet.net
> Sent: 23 August 2004 11:35
> To: mathgroup at smc.vnet.net
> Subject: [mg50267] [mg50263] Conditonal sum
> 
> 
> I am new to mathematica and could really need a tip on how to 
> implement a 
> conditional sum.  Pseudocode would be something like this
> 
> 
> EndSum=a;
> if j in Sm:
> 	EndSum=EndSum+f[j]
> end
> 
> 
> I have tried doing this by using an If-clause inside the 
> sum-function, but  
> 
> this seems little elegant and is nor very suitable for 
> symbolic calculations.
> 
> Any advice would be highly appreciated
> 
> Christopher Grinde
> 


  • Prev by Date: Re: Conditonal sum
  • Next by Date: Re: 3D Screensavers for Mathematica users
  • Previous by thread: Re: Conditonal sum
  • Next by thread: Re: Conditonal sum