Qiang Li
Qiang Li

Reputation: 10865

How to do substitution of a function in mathematica

I have the expression D[f[x, y], x], and I want to substitute f[x,y] with x*y, I tried the following:

D[f[x, y], x] /. {f[x,y] -> x*y} and D[f[x, y], x] /. {f -> x*y}

But neither worked. Would appreciate your help! Thanks.

Upvotes: 11

Views: 12779

Answers (3)

Cetin Sert
Cetin Sert

Reputation: 4600

You can also try Hold and Release or Defer etc.

Hold@D[f[x, y], x] /. {f[x, y] -> x*y}

D[x y, x]    


Hold@D[f[x, y], x] /. {f[x, y] -> x*y} // Release

y

Upvotes: 2

Dr. belisarius
Dr. belisarius

Reputation: 61046

Nothing new, just the way I usually think of it:

D[f[x, y], x] /. f -> Function[{x, y}, x y]

Out

y

Upvotes: 8

Leonid Shifrin
Leonid Shifrin

Reputation: 22579

The FullForm of the derivative in your expression is

In[145]:= D[f[x,y],x]//FullForm

Out[145]//FullForm= Derivative[1,0][f][x,y]

This should explain why the first rule failed - there is no f[x,y] in your expression any more. The second rule failed because Derivative considers f to be a function, while you substitute it by an expression. What you can do is:

In[146]:= D[f[x,y],x]/.f->(#1*#2&)

Out[146]= y

Note that the parentheses around a pure function are essential, to avoid precedence - related bugs.

Alternatively, you could define your r.h.s through patterns:

In[148]:= 
fn[x_,y_]:=x*y;
D[f[x,y],x]/.f->fn

Out[149]= y

HTH

Upvotes: 16

Related Questions