2
$\begingroup$

If I have an expression in terms of multiplications of (pairs of) variables, e.g. $x_1$ ... $x_N$ such that the expression I want to manipulate is of the form

$A_{1,1}x_1^2+A_{1,2}x_1x_2+\ldots + A_{N,N-1}x_{N-1}x_N+A_{N,N}x_N^2$

What is the easiest way to implement the custom replacement rules

$x_ix_j\to C_{i,j}$

which can't be achieved with simple algebraic replacements for the individual $x_i$ (For instance $x_ix_j$ might represent the product of two random variables such that the replacement rules effect an expectation and thus give a correlation, i.e. $x_i^2\to \mathbb{E}[x_i^2]=\rho_i$ whilst $x_ix_j\to\mathbb{E}[x_ix_j]=0$, for example)?

Practically, I might have $x_1,\ldots,x_4$, say, but very large expressions that make manual substitution tedious.

$\endgroup$
2
  • $\begingroup$ If what you want for your actual project is an algorithm for Wick contractions of Gaussian variables there are answers for that here on stack exchange, one of which I use regularly. $\endgroup$ Dec 21, 2022 at 17:18
  • $\begingroup$ If all of the $x_i$ random variables have the same distribution, you might want to consider getting familiar with PowerSymmetricPolynomial, AugmentedSymmetricPolynomial, SymmetricPolynomial, and MomentConvert. $\endgroup$
    – JimB
    Dec 22, 2022 at 1:22

4 Answers 4

4
$\begingroup$

I think you want something like the following (?)

Sum[A[i, j] x[i] x[j], {i, 1, 2}, {j, 1, 2}] /. {x[i_] x[j_] -> 
   c[i, j], x[i_] x[i_] -> c[i, i]}

res

$\endgroup$
4
$\begingroup$

As a possibility, let:

expr = a[1, 1] x[1]^2 + a[1, 2] x[1] x[2] + a[2, 3] x[2] x[3]

rule = {Times[y__, x_[a_Integer] x_[b_Integer]] :> y C[a, b]
   , Times[y__, x_[a_Integer] x_[a_Integer]] :> y G[a, a]
    };

Test:

expr /. rule
a[1, 2] C[1, 2] + a[2, 3] C[2, 3] + a[1, 1] G[1, 1]
$\endgroup$
3
$\begingroup$

I'm not sure whether this would work for you here, but this reminds me of similar cases where Plus and Times would give me headaches. An easy fix was to just replace as expr /. Times -> times (and/or Plus to plus), do whatever, and replace back when you're ready.

(I believe this is also the idea behind Deactivate and related functions, but they seemed slightly more finicky to me.)

$\endgroup$
3
$\begingroup$

Try the following. Here is your polynomial:

expr = Sum[
  Subscript[A, i, j]*Subscript[x, i]*Subscript[x, j], {i, 1, 5}, {j, 
   1, 5}]

enter image description here

Here is the replacement:

expr /. {Subscript[x, i_]*Subscript[x, j_] -> Subscript[c, i, 
   j], \!\(
\*SubsuperscriptBox[\(x\), \(i_\), \(2\)] -> 
\*SubscriptBox[\(c\), \(i, i\)]\)}

with the following effect

enter image description here

Have fun!

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.