Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2004

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

Search the Archive

Re: Conditonal sum

  • To: mathgroup at
  • Subject: [mg50309] Re: [mg50263] Conditonal sum
  • From: "David Annetts" <davidannetts at>
  • Date: Thu, 26 Aug 2004 06:51:01 -0400 (EDT)
  • Sender: owner-wri-mathgroup at

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

if j in Sm:

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

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.



  • Prev by Date: Opposite of ReadList[ ... ,Byte]?
  • Next by Date: Re: Re: Technical Publishing Made Easy with New Wolfram Publicon Software
  • Previous by thread: Re: Conditonal sum
  • Next by thread: Selecting cubic roots in functional form