Matlab differentiate an inline function

2.3k views Asked by At

How can I differentiate my Function Fun? When I try to use diff it says

'diff' is not supported for class 'inline'

The code I used is shown below:

fprintf('Newton Raphson\n');

Fun=input('\nType a function \n');
xi=input('\nType initial value\n');

def=diff(Fun);

der=inline(def);

dxi=der(xi);
2

There are 2 answers

2
rayryeng On

Marcin is correct. Don't use inline functions. Those are no longer used. If you want to differentiate using the Symbolic Math Toolbox, use sym to create a function for you, then use this to differentiate it.

As such, do something like this, assuming that x is the independent variable:

syms x;
fprintf('Newton Raphson\n');

Fun=input('\nType a function \n');
xi=input('\nType initial value\n');

out = sym(Fun);
def = diff(out);
dxi = subs(def, 'x', xi);

Note that because the formula is symbolic, if you want to substitute x with a particular value, you would need to use subs. With subs, we are replacing x with our initial value stored in xi.


Let's do a run-through example. Here's what I get when I run this code, with my inputs and outputs:

Newton Raphson

Type a function 
x^2 + x + 3

Type initial value
4

out would be the function that was input in:

out =

x^2 + x + 3

xi would be the initial value:

xi =

4

The derivative of the function is stored in def:

def =

2*x + 1

Finally, substituting our initial value into our derivative is stored in dxi, and thus gives:

dxi =

9

Good luck!

0
CODEsimply On

See this might help you.

eq   = input('Write an equation in x','s'); %input a equation
f    = sym(eq);                             %turn the equation into a symbolic one
fin  = inline(char(f));                     %for converting the symbolic function into inline funct
dfin = inline(char(diff(f)));               %for converting the symb diff func into inline diff f