2
$\begingroup$

It's an extremely brief question. I want to replace all variables in an expression to another ones, say $x \rightarrow y$. But the command

x + Subscript[a, x] /. x -> y

replaces also the subscript. How can I do replacements while leaving the Subscript object unchanged?

$\endgroup$
4
$\begingroup$

When you want to do replacements with a pattern that shouldn't be changed, I like to use multiple replacement rules (as in this answer):

ReplaceAll[
    x + Subscript[a, x],
    {
        s_Subscript :> s, (* pattern to avoid *)
        x -> y
    }
]

y + Subscript[a, x]

$\endgroup$
  • 1
    $\begingroup$ Thanks. It's bit more general solution, thus it suits me better then the answer above. $\endgroup$ – Artem Zefirov Apr 11 '18 at 19:36
  • 1
    $\begingroup$ It may be worth quoting the documentation to explain why this works: "The first rule that applies to a particular part is used; no further rules are tried on that part or on any of its subparts." $\endgroup$ – Alan Apr 12 '18 at 1:46
1
$\begingroup$

It's an extremely brief answer:

x + Subscript[a, x] /. Subscript[a_, x] :> Subscript[a, z] /. {x -> y, z -> x}
$\endgroup$
  • $\begingroup$ Thanks. Could you clarify briefly whether the command x + Subscript[a, x] /. Subscript[a, x] -> Subscript[a, z] /. {x -> y, z -> x} is wrong. That is, can we replace function-like notation a_ with a, and delayed reduce :> with a simple reduce symbol -> ? $\endgroup$ – Artem Zefirov Apr 11 '18 at 18:55
  • $\begingroup$ It works but only for subsripts of a. So, it does not work for Subscript[b_, x], for example. $\endgroup$ – Henrik Schumacher Apr 11 '18 at 18:57
  • $\begingroup$ Anyway, your answer is witty. I thought, that there should be something more straightforward. $\endgroup$ – Artem Zefirov Apr 11 '18 at 19:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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