0
$\begingroup$
x y''[x]+2y'[x]+l^2 x y[x]==0/.y[x]->Cos[x]

I think above code shows what I want to do quite clearly. How do I make it happen. Only y[x] is replaced.

$\endgroup$
  • $\begingroup$ Try y -> Cos. $\endgroup$ – J. M. will be back soon Jun 6 '15 at 8:32
  • $\begingroup$ For more general usage you can use dChange like: dChange[ x y''[x] + 2 y'[x] + l^2 x y[x] == 0, y[x] == Cos[x] ]. 80241 - feedback appreciated. $\endgroup$ – Kuba Jun 6 '15 at 8:34
  • $\begingroup$ @Guesswhoitis. what if I wanted to change it into Cos^2 ? $\endgroup$ – grdgfgr Jun 6 '15 at 8:36
  • 3
    $\begingroup$ Then you do y -> Function[x, Cos[x]^2] $\endgroup$ – J. M. will be back soon Jun 6 '15 at 8:39
  • $\begingroup$ thanks, make that into an answer so that the question doesnt remain unanswered $\endgroup$ – grdgfgr Jun 6 '15 at 8:42
3
$\begingroup$

This question has been asked for times, Evaluation of Derivative in a Module and Replace rule with function? Derivatives don't evaluate.

Here are several ways to solve it:

If you do not mind pollute Global namespace, assign the function first.

y[x_] = Cos[x]
x y''[x] + 2 y'[x] + l^2 x y[x] == 0

If you mind, assign it in a Block

Block[{y}, y[x_] = Cos[x];   
x y''[x] + 2 y'[x] + l^2 x y[x] == 0]

or, replace it by a pure function:

x y''[x] + 2 y'[x] + l^2 x y[x] == 0 /. y -> Function[x, Cos[x]]

If you are trying to do something more complex, then these methods will fail:

In[1]:= F[func_] := Block[{y}, y[x_] = func;
  x y''[x] + 2 y'[x] + l^2 x y[x] == 0]

In[2]:= F[Cos[x]]

Out[2]= l^2 x Cos[x] == 0

and

In[1]:= F[func_] := x y''[x] + 2 y'[x] + l^2 x y[x] == 0 /. y -> Function[x, func]

In[2]:= F[Cos[x]]

Out[2]= l^2 x Cos[x] == 0

The methods in the link will work:

In[7]:= F[func_] := 
 Block[{y, e}, e = x y''[x] + 2 y'[x] + l^2 x y[x] == 0;
    e /. y -> Function[x, #]] &[func]

In[8]:= F[Cos[x]]

Out[8]= -x Cos[x] + l^2 x Cos[x] - 2 Sin[x] == 0

or

In[11]:= F[func_] := 
 x y''[x] + 2 y'[x] + l^2 x y[x] == 0 /. y -> Function[x, #] &[func]

In[12]:= F[Cos[x]]

Out[12]= -x Cos[x] + l^2 x Cos[x] - 2 Sin[x] == 0

I do not quite understand why the last two methods work, I hope someone can explain it in this answer.

$\endgroup$

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.