# Selective substitution into an expression

I have the following mathematical expression

$$F = \frac{1}{6}\left[\sum_{j=1}^{M-1}(\phi_{j+1}+\cdots+\phi_{M})S_{j}\right]^3$$

and I would like to evaluate this in Mathematica using the following rules

$S_{j}\cdot S_{j}\cdot S_{j} = 8$

$S_{j}\cdot S_{j+1}\cdot S_{j+1} = 2j$

$S_{j}\cdot S_{j+1}\cdot S_{j} = -(2j+2)$

What I have so far is:

How do I implement these rules in the evaluation of the cubic power?

• Please, do not post images of your code, but your code in a way we can edit and test it. Read the help in MMA stackexchange to how to post your code... Dec 19, 2017 at 20:17

sumin[m_, j_] := Sum[ϕ[k], {k, j + 1, m}]
sumout[m_] := Sum[sumin[m, j] S[j], {j, 1, m - 1}]


Using ReplaceRepeated with rules

rplcmntrules = {Power[S[_], 3] :> 8,
S[j_] Power[S[k_], 2] /; k == j + 1 :> 2 j,
S[k_] Power[S[j_], 2] /; k == j + 1 :> - (2 j + 2) };

ExpandAll[sumout[4]^3] //. rplcmntrules /. (f : (S | ϕ))[x_] :> Subscript[f, x] // TeXForm


$\small 3 S_1^2 S_3 \phi _4 \phi _2^2+3 S_1 S_3^2 \phi _4^2 \phi _2+6 S_1^2 S_3 \phi _4^2 \phi _2+6 S_1 S_2 S_3 \phi _4^2 \phi _2+6 S_1^2 S_3 \phi _3 \phi _4 \phi _2+6 S_1 S_2 S_3 \phi _3 \phi _4 \phi _2+3 S_1 S_3^2 \phi _4^3+3 S_1^2 S_3 \phi _4^3+6 S_1 S_2 S_3 \phi _4^3+3 S_1 S_3^2 \phi _3 \phi _4^2+6 S_1^2 S_3 \phi _3 \phi _4^2+12 S_1 S_2 S_3 \phi _3 \phi _4^2+3 S_1^2 S_3 \phi _3^2 \phi _4+6 S_1 S_2 S_3 \phi _3^2 \phi _4+8 \phi _2^3+12 \phi _3 \phi _2^2+12 \phi _4 \phi _2^2+6 \phi _3^2 \phi _2+6 \phi _4^2 \phi _2+12 \phi _3 \phi _4 \phi _2+10 \phi _3^3+12 \phi _4^3+6 \phi _3 \phi _4^2+12 \phi _3^2 \phi _4$

Another way (with $m=4$), probably less elegant:

sum = Expand@(1/6 Sum[Sum[Subscript[\[Phi], i], {i, j + 1, m}]*Subscript[S,j],
{j, 1, m - 1}]^3 /. m -> 4)


Generate the rules:

rules = Flatten@(Table[{Subscript[S, j]^3 -> 8,
Subscript[S, j]*Subscript[S, j + 1]^2 -> 2 j ,
Subscript[S, j]^2*Subscript[S, j + 1] -> -2 (j + 1)}, {j, 1,
m - 1}] /. m -> 4)


Replace:

sum /. rules


$\frac{1}{2} S_1^2 S_3 \phi _4 \phi _2^2+\frac{1}{2} S_1 S_3^2 \phi _4^2 \phi _2+S_1^2 S_3 \phi _4^2 \phi _2+S_1 S_2 S_3 \phi _4^2 \phi _2+S_1^2 S_3 \phi _3 \phi _4 \phi _2+S_1 S_2 S_3 \phi _3 \phi _4 \phi _2+\frac{1}{2} S_1 S_3^2 \phi _4^3+\frac{1}{2} S_1^2 S_3 \phi _4^3+S_1 S_2 S_3 \phi _4^3+\frac{1}{2} S_1 S_3^2 \phi _3 \phi _4^2+S_1^2 S_3 \phi _3 \phi _4^2+2 S_1 S_2 S_3 \phi _3 \phi _4^2+\frac{1}{2} S_1^2 S_3 \phi _3^2 \phi _4+S_1 S_2 S_3 \phi _3^2 \phi _4+\frac{4 \phi _2^3}{3}+2 \phi _3 \phi _2^2+2 \phi _4 \phi _2^2+\phi _3^2 \phi _2+\phi _4^2 \phi _2+2 \phi _3 \phi _4 \phi _2+\frac{5 \phi _3^3}{3}+2 \phi _4^3+\phi _3 \phi _4^2+2 \phi _3^2 \phi _4$