1
$\begingroup$

My question is that in Mathematica notebook when I write replacing commands, it didn't replace.

In[1]:= 2*x+y+1/.(x+y)->0
Out[1]:=1+2x+y

or

In[2]:= x+x+y+1/.(x+y)->0
Out[2]:=1+2x+y
$\endgroup$
  • $\begingroup$ For the second this works HoldForm[x + x + y + 1] /. (x + y) -> 0 $\endgroup$ – mattiav27 Jan 7 at 10:05
3
$\begingroup$

ReplaceAll is not designed to do algebra, which does not try any algebraic transform. But Reduce etc. can do them.

However, I still can make something work with ReplaceAll.

For the first line, it's not replaced because there isn't any x+y at all, as you can see that with FullForm:

Plus[1,Times[2,x],y]

I recommend this command:

/. y->-x

For the second line, there is a x+y in x+x+y+1. But it's evaluated and then turns to 2x+y+1. You can use Hold to forbid it to be evaluated, and then use ReleaseHold after replacing:

ReleaseHold[Hold[x + x + y + 1] /. (x + y) -> 0]

For more convinience, use Unevaluated to hold it just once:

Unevaluated[x + x + y + 1] /. (x + y) -> 0

To break 2x to x+x, try:

Apply[Unevaluated@*Plus, Table[#2, #1] & @@ (2 x)]
$\endgroup$
  • $\begingroup$ Thank you Sir, Is there any command to break 2*x= x+x? $\endgroup$ – Habib Ullah Jan 7 at 8:31
  • $\begingroup$ @HabibUllah No. You can imagine that: even if there is a function converting a scalar product to a sum, the result will finally be evaluated to be a product. So such a function is useless. But you can use non-standard evaluation as: Table[#2,#1]&@@(2x), and replace its head List by Plus when needed. $\endgroup$ – bcegkmqs23 Jan 7 at 8:58
  • $\begingroup$ Thank you so much for your kind suggestions. $\endgroup$ – Habib Ullah Jan 7 at 10:14
1
$\begingroup$

You could like this:

z /. ToRules[Reduce[z == 2 x + y + 1 && x + y == 0, {z, y}]]

which yields:

1 + x

$\endgroup$
  • $\begingroup$ Thank you so much. $\endgroup$ – Habib Ullah Jan 7 at 8:05
  • $\begingroup$ @HabibUllah Welcome to MSE. There are many ways to achieve your goal.. You can choose the way that best suits your purposes. Good luck:) $\endgroup$ – ubpdqn Jan 7 at 8:07

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.