Re: Grouping similar indices together in an expression
- To: mathgroup at smc.vnet.net
- Subject: [mg65258] Re: Grouping similar indices together in an expression
- From: Paul Abbott <paul at physics.uwa.edu.au>
- Date: Wed, 22 Mar 2006 06:13:49 -0500 (EST)
- Organization: The University of Western Australia
- References: <dvosko$j5k$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
In article <dvosko$j5k$1 at smc.vnet.net>,
"David Sanders" <dpsanders at gmail.com> wrote:
> I am a newbie in Mathematica, and am trying to do the following.
>
> I have terms which look like
> a[i] a[j] b[i] b[j]
>
> I need to apply a function F, for which I need to group the different
> indices (by which I mean i, j) together as follows:
>
> F(a[i] a[j] b[i] b[j]) = F(a[i] b[i]) F(a[j] b[j])
What is the application? Knowing this might help construct the "best"
solution.
> I do not in general know how many different indices there might be in a
> term. E.g. I might have
> a[i] a[j] a[k] b[j]
>
> Could somebody please give me a hint as to how to do this?
Essentially, you want to sort the expression by its index. You could use
pattern-matching to do this. Alternatively, Sort can be used for this
with a suitable ordering function. However, Times is Orderless so you
need to change the head of the expression to, say, List:
Sort[List @@ (a[i] a[j] a[k] b[j]), OrderedQ[{First[#1], First[#2]}] &]
Now you can use Split to split up the expression whenever the index
changes:
Split[%, First[#1] === First[#2] &]
Putting these together, the function IndexCollect applies f to each
grouping of indices:
IndexCollect[f_, x_] := Head[x] @@ f /@ Head[x] @@@
Split[Sort[List @@ x, OrderedQ[{First[#1], First[#2]}] &],
First[#1] === First[#2] &]
For example,
IndexCollect[f, a[i] a[j] b[i] b[j]]
f[a[i] b[i]] f[a[j] b[j]]
IndexCollect[f, a[i] a[j] a[k] b[j]]
f[a[i]] f[a[k]] f[a[j] b[j]]
Also, if you have addition instead of multiplication, this operation is
preserved (via Head[x] in the definition of IndexCollect):
IndexCollect[f, a[i]+a[j]+a[k]+b[j]]
f[a[i]] + f[a[k]] + f[a[j] + b[j]]
Cheers,
Paul
_______________________________________________________________________
Paul Abbott Phone: 61 8 6488 2734
School of Physics, M013 Fax: +61 8 6488 1014
The University of Western Australia (CRICOS Provider No 00126G)
AUSTRALIA http://physics.uwa.edu.au/~paul