MathGroup Archive 2006

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

Search the Archive

Re: Grouping similar indices together in an expression

  • To: mathgroup at
  • Subject: [mg65277] Re: Grouping similar indices together in an expression
  • From: "David Sanders" <dpsanders at>
  • Date: Thu, 23 Mar 2006 06:58:44 -0500 (EST)
  • References: <dvosko$j5k$>
  • Sender: owner-wri-mathgroup at


Thanks very much to everyone for their replies. I've certainly learnt a
lot about Mathematica by looking at them!

I apologise for not explaining the problem clearly; I was trying to
reduce it to its essentials, but went too far.

The "indices" i, j etc. represent positions, and are integers.  a[i]
etc. are random variables associated to those positions.  The random
variables at different positions (with different indices) are
independent, but those at the same position are not.  The function
which I wrote as "F" is an expectation; I will now write it as Ex.

What I need to calculate is the expectation of terms such as
a[i]^2 a[i+1] b[i] b[i+1].
This is a product of random variables which take real values.
The terms can be raised to positive integer powers and the indices can
be things like i+1, representing the position next to position i.

I thus need
Ex[ a[i]^2 a[i+1] b[i] b[i+1] ] = Ex[ a[i]^2 b[i] ]  Ex[ a[i+1] b[i+1]

Using everybody's suggestions, I have put together the following code
to do this:

ExtractIndex[term_] := If[Head[term]===Power, term[[1,1]], term[[1]]]

ExtractIndices[expr_] :=
  If[Head[expr] =!= Times, {ExtractIndex[expr]},
    Union[Map[ExtractIndex, Apply[List, expr]]]]

MakeList[expr_] := If[Head[expr] === Times, Apply[List, expr], {expr}]

ExtractTerms[expr_, index_] :=
  Ex[Apply[Times,Select[MakeList[expr], ExtractIndex[#] \[Equal]

Expec[expr_] :=
  Apply[Times,MapThread[ExtractTerms[expr, #]&,

Expec[a_+b_] := Expec[a] + Expec[b]


Expec[ a[i] a[j] b[i] b[j] + a[i+1] a[j] b[i+1] b[j] ]


Ex[a[i]^2 b[i]] Ex[a[j] b[j]] + Ex[a[1+i] b[1+i]] Ex[a[j] b[j]]

as desired.

Now what I need to do is tell Mathematica the rules for computing the
expectations at a site.  For simplicity let us suppose that they
factorise, even though in my real application that is not the case.

Then I want something like
Ex[a[i_]^alpha_ b[i_]^beta_] = A^alpha B^beta

But this does not capture e.g. Ex[a[i] b[i]].  How can I include these
without giving them explicitly?

Apologies for the length of this post,
Best wishes,


  • Prev by Date: Re: How to sample a 2-dim. r.v. with known density function?
  • Next by Date: Re: A question concerning Show and PlotLegend
  • Previous by thread: Re: Grouping similar indices together in an expression
  • Next by thread: Quotient group/space notation