Question

I have the following anonymous function:

f = @(x)x^2+2*x+1

I'm using this so that I use it in the following way:

f(0) = 1

But what if I want to find the derivative of such a function while still keeping it's anonymous function capability? I've tried doing the following but it doesn't work:

f1 = @(x)diff(f(x))

but this just returns

[]

Any thoughts on how to accomplish this?

Of course I could manually do this in 3 seconds but that's not the point...

Was it helpful?

Solution 2

When you do diff of a vector of n elements it just outputs another vector of n-1 elements with the consecutive differences.. so when you put a 1 element vector you get an empty one.

A way to go would be to decide an epsilon and use the Newton's difference quotient:

epsilon = 1e-10;
f = @(x) x^2+2*x+1;
f1 = @(x) (f(x+epsilon) - f(x)) / epsilon;

or just do the math and write down the formula:

f1 = @(x) 2*x+2;

http://en.wikipedia.org/wiki/Numerical_differentiation

OTHER TIPS

If you have symbolic math toolbox, you can use symbolic functions to achieve the desired as follows:

syms x
myFun=x^2+2*x+1;
f=symfun(myFun,x);
f1=symfun(diff(f),x);

%Check the values
f(2)
f1(2)

You should get 9 and 6 as answers.

@jollypianoman this works to me. Actually you need to say that the symfun has to be evaluate using eval command, then you get all the features of an anonymous function. the best is to read the example below...

clear
N0=1;N1=5;
N=@(t) N0+N1*sin(t);
syms t
Ndot=symfun(diff(N(t)),t); 
Ndot_t=@(t) eval(Ndot);
Ndot_t(0)

ans = 5

Ndot_t(1)

ans = 2.7015

[tstop] = fsolve(Ndot_t,pi/3)
tstop =

     1.5708

cheers, AP

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top