3

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.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • 1
    (1) You are confusing anonymous functions with symbolic functions. You need to define `f` as a symbolic function. (2) MATLAB or Octave? You say MATLAB but your code is Octave. The two are different, especially for symbolic stuff. If you want an Octave solution, don’t say MATLAB and don’t tag MATLAB. – Cris Luengo Apr 08 '21 at 18:41

2 Answers2

3

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.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • Alternatively, if `x=4` on the workspace, you can simply call `eval(df)`. – Tasos Papastylianou Apr 09 '21 at 09:11
  • @Tasos: That is what the docs say, but it gave me an error message. Maybe I need to upgrade Octave or Python or something, I dunno. The machine that has Octave is stuck on Ubuntu 18 and therefore stuck with older versions of software. :/ – Cris Luengo Apr 09 '21 at 13:03
1

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)
MichaelTr7
  • 4,737
  • 2
  • 6
  • 21
  • 1
    This is compatible with octave too. The symbolic package includes `@sym/matlabFunction` as an alias to `@sym/function_handle`, for compatibility with matlab. – Tasos Papastylianou Apr 09 '21 at 09:13