Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I know a similar question is answered somewhere, but it doesn't work for my case for some reason. I have the following problem in Mathematica. I want to compute f[h[x]]= x^2 + D[h[x],x]. Here, h[x] can be some function of x, say Sin[x]. I have written the following code in Mathematica,

SetAttributes[{f, D}, HoldAll]
f[h_, x_] := x^2 + D[h[x], x]
h := Sin[x]

But then the output of

f[h, 10]

is an error "General::ivar: 10 is not a valid variable."

Any better way of doing the composition of functions in Mathematica?

  • Sarah
share|improve this question
    
@b.gatessucks, Thanks. But I was aiming for some generic function rather than only Sin. In particular, the actual h[x] in my case is a quite complicated function. –  John May 20 at 18:41
    
You mean, f[h[#] &, x_] := x^2 + D[h[x], x] h[x_] := Sin[x] ? In that case, f[h[10], 10] just returns f[h[10], 10]. –  John May 20 at 18:47
add comment

1 Answer 1

You can define :

f2[h_, x_] := x^2 + Derivative[1][h][x]

Then :

(* Specific function, generic x *)
h1[x_] = Sin[x];
f2[h1, x]
(* x^2 + Cos[x] *)     

(* Generic function, numeric x *)
f2[h, 10]
(* 100 + Derivative[1][h][10]*)

(* Generic function, generic x *)
f2[g, x]
(* x^2 + Derivative[1][g][x] *)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.