Re: Conditonal sum
- To: mathgroup at smc.vnet.net
- Subject: [mg50309] Re: [mg50263] Conditonal sum
- From: "David Annetts" <davidannetts at ihug.com.au>
- Date: Thu, 26 Aug 2004 06:51:01 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
Hi Christopher, 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 -------------------- I suggest looking at Select, then applying Plus to the results of Select. mylist = Table[Random[Real, {-5, 5}], {100}]; Plus @@ Select[mylist, (# > 0 &)] (* Sum of +ve numbers *) Plus @@ Select[mylist, (-2 < # < 2) &] (* Sum of numbers in range *) Another way might be through NestList. Again, we can apply Plus to the resulting list. For example, the code below sums the first 8 powers of 2 ... Plus @@ NestList[2 # &, 1, 8] The downside to Select (& NestList, as well as a lot of other functional programming) is that it is often less intuitive than the Fortran (or C++) approach of doing things in a loop. The upside, as far as Mathematica is concerned, is that the functional approach is often much faster. Regards, Dave.