2
$\begingroup$

I have an expression, $$test=\left(x_{jv}-y_{jv}\right)b+\left(x_{im}-y_{im}\right)c$$

Format[subs[body_, sub_]] := Subscript[body, sub]
Format[x[a_, b_]] := Subscript[x, Row@{a, b}]
Format[y[a_, b_]] := Subscript[y, Row@{a, b}]
test=(x[j,v]-y[j,v])b+(x[i,m]-y[i,m])c

Is there a way to replace all terms of form (x-y) with z using the following rule:

x[j_,v_]-y[j_,v_]:=z[j,v]

at once.

$\endgroup$
4
  • $\begingroup$ Have you tried to use ReplaceAll? $\endgroup$ Aug 20, 2021 at 5:50
  • $\begingroup$ What I meant is with a rule. Else I need to use ReplaceAll to replace all terms one by one $\endgroup$
    – Jasmine
    Aug 20, 2021 at 5:51
  • 1
    $\begingroup$ This is literally what ReplaceAll is created to do... And you don't have to do it term by term, you can use it on entire expressions like test. $\endgroup$ Aug 20, 2021 at 5:53
  • $\begingroup$ Exactly what I am looking for . Thanks $\endgroup$
    – Jasmine
    Aug 20, 2021 at 5:59

1 Answer 1

1
$\begingroup$

Try this:

test /. x[j_, v_] - y[j_, v_] -> z[j, v]


(*  c z[i, m] + b z[j, v]  *)
$\endgroup$
4
  • $\begingroup$ If the expression is initially expanded, I do not think this would work & one would likely need to solve for a replacement in terms of either x or y, in this case. $\endgroup$ Aug 20, 2021 at 13:07
  • 1
    $\begingroup$ @ CA Trevillian It is always better to look for a replacement such as x[j_, v_] -> z[j, v]+-y[j, v]. That's well-known and elementary to work out given the OP knows how to apply the rule. However, the OP asked for this precise replacement. $\endgroup$ Aug 20, 2021 at 16:36
  • $\begingroup$ That is precisely what I was trying to say, well stated! This question is asked quite often in many different forms, so it might be better to recommend a “best practices” approach such as that in your comment, rather than to do otherwise & possibly perpetuate the confusion among users. $\endgroup$ Aug 20, 2021 at 16:43
  • 1
    $\begingroup$ @CA Trevillian Yes and no. I often do such replacements and use one or another way depending on how the expression looks like. The latter approach is more general, right, but the former one is faster to apply by copy-paste. $\endgroup$ Aug 20, 2021 at 16:55

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.