Derivative of symbolic function at a specific value

Viewed 197

I am trying to use this code in Octave to evaluate the derivative of function f, df, at specific x values:

pkg load symbolic;
syms x;
f = @(x) sqrt(2*x+1) - sqrt(x+4);
disp(f);
df = diff(f,x);

I tried df(4) for example, and eval(df,4), but neither of them worked giving a syntax or another errors.

The main function of this code is to then use those values to find the function f root using the Newton-Raphson method.

2 Answers

You confuse anonymous functions with symbolic functions. Your f is an anonymous function. It doesn't use the symbolic variable x because x is local within this function, it's an input argument. The function will numerically evaluate any input you give it.

Define a symbolic function as follows:

pkg load symbolic

syms x
f = sqrt(2*x+1)-sqrt(x+4)
df = diff(f,x)

Output:

>> f = sqrt(2*x+1)-sqrt(x+4)
f = (sym)

      _______     _________
  - ╲╱ x + 4  + ╲╱ 2⋅x + 1

>> df = diff(f,x)
df = (sym)

       1             1
  ─────────── - ───────────
    _________       _______
  ╲╱ 2⋅x + 1    2⋅╲╱ x + 4

To evaluate the function for a given x, you can use subs and cast the result to double:

double(subs(df,x,4))

This returns the value 0.15656.

In MATLAB

A possibility might be to change the function df into a anonymous function/function handle by using the matlabFunction() function to do the conversion from:

Symbolic → Anonymous Function/Function Handle

Using the subs() function may also work but I find it less elegant.

syms x
f = sqrt(2*x+1) - sqrt(x+4);
df = diff(f,x);
df = matlabFunction(df);

df(4)
Related