Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 597
Qiang Li Avatar asked Feb 11 '11 23:02

Qiang Li


2 Answers

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

like image 198
Leonid Shifrin Avatar answered Sep 19 '22 16:09

Leonid Shifrin


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

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

Out

y
like image 24
Dr. belisarius Avatar answered Sep 20 '22 16:09

Dr. belisarius