Quick to the point:is there a way to make Mathematica assume that $a \neq a[1] \neq a[2] , ...$ I notice that Solve assumes that $a$ is the same for all $a[1],a[2],...$ Also, if I replace $a \rightarrow b$ then I get all the $b[1],b[2],..$ for the whole expression.
1 Answer
Quoting from one of the comments above:
However, when you take the solution provided by
Solve[{x + x[2] == 1}, {x}]
and plug back to the equation you get something like(1- x[2] + (1-x[2])[2])
, that is the main issue I'm having.
The easy fix is just changing x to something like x1 before using Solve
but that might be a problem if the expressions are lengthy . Here are some replacement rules that change x to x1 while keeping x[2]:
Reference:
Expand[(x + Cos[x[2] + x]*x[2]*x + Sin[x[3]*x])^2 + x]
x+x^2+2 x Sin[x x[3]]+Sin[x x[3]]^2+2 x^2 Cos[x+x[2]] x[2]+2 x Cos[x+x[2]] Sin[x x[3]] x[2]+x^2 Cos[x+x[2]]^2 x[2]^2
- Option 1
Straightforward but clunky as it introduces an auxiliary variable:
expression1=
(Expand[(x + Cos[x[2] + x]*x[2]*x + Sin[x[3]*x])^2 + x]
/. x[s_] :> b[s] /. x :> x1 /. b :> x)
x1+x1^2+2 x1 Sin[x1 x[3]]+Sin[x1 x[3]]^2+2 x1^2 Cos[x1+x[2]] x[2]+2 x1 Cos[x1+x[2]] Sin[x1 x[3]] x[2]+x1^2 Cos[x1+x[2]]^2 x[2]^2
- Option 2
Quick but mysterious :
expression2=
(Expand[(x + Cos[x[2] + x]*x[2]*x + Sin[x[3]*x])^2 + x]
/. {x -> x1, x[s_] :> x[s]});
It's not entirely clear to me why that works. I think it's because ReplaceAll
works from the outside in as explained here https://mathematica.stackexchange.com/a/188608/86543 but I feel unsafe using that as I am not entirely sure.
- Option 3
Convenient:
(The code below uses the resource function ReplaceAllOutside)
expression3=
(Expand[(x + Cos[x[2] + x]*x[2]*x + Sin[x[3]*x])^2 + x] //
ResourceFunction["ReplaceAllOutside"][x :> x1, x[_]]);
Check:
expression1 == expression2 == expression3
True
Solve[{x[1] + x[2] == 1, x[1] - x[2] == 2}, {x[1], x[2]}]
? $\endgroup$Solve[{x + x[2] == 1}, {x}]
and plug back to the equation you get something like(1- x[2] + (1-x[2])[2])
, that is the main issue I'm having. $\endgroup$Solve[x[1] + x[2] == 1, x[1]]
orSolve[x1 + x[2] == 1, x1]
. If you already have a long code where you usedx
andx[2]
you can donewEquation=oldEquation/.x->x1
solvenewEquation
and then revert back to the previous notation usingx1->x
whenever you need, $\endgroup$x1[2]
. $\endgroup$