4

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?

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
Artem Zefirov
  • 361
  • 1
  • 11

2 Answers2

6

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]

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
  • 1
    Thanks. It's bit more general solution, thus it suits me better then the answer above. – Artem Zefirov Apr 11 '18 at 19:36
  • 1
    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." – Alan Apr 12 '18 at 01:46
1

It's an extremely brief answer:

x + Subscript[a, x] /. Subscript[a_, x] :> Subscript[a, z] /. {x -> y, z -> x}
Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
  • 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 -> ? – Artem Zefirov Apr 11 '18 at 18:55
  • It works but only for subsripts of a. So, it does not work for Subscript[b_, x], for example. – Henrik Schumacher Apr 11 '18 at 18:57
  • Anyway, your answer is witty. I thought, that there should be something more straightforward. – Artem Zefirov Apr 11 '18 at 19:03