Warm tip: This article is reproduced from serverfault.com, please click

How to find differential of input function while writing in MATLAB for Newton Raphson method

发布于 2020-11-27 17:05:13

I have been searching for a way to differentiate a function, input by the user and apply differentiation on it as peruse of Newton Raphson Method, but since the inline functions are not recommended, is there any way to take the user's input in symbolic function then and there? I tried converting inline into sym but this code:

a=input('Enter function with right hand side zero:','s');
x(1)=input('Enter Initial Guess:');
Es=input('Enter allowed Error:');

f=inline(a)
dif=diff(sym(a));
d=inline(dif);

for i=1:100
    x(i+1)=x(i)-((f(x(i))/d(x(i))));
    err(i)=abs((x(i+1)-x(i))/x(i));
    if err(i)<error
        break
    end
end
disp(x(i));

gives this error after taking every argument:

Error using sym>convertChar (line 1557)
Character vectors and strings in the first
argument can only specify a variable or
number. To evaluate character vectors and
strings representing symbolic expressions, use
'str2sym'.

Error in sym>tomupad (line 1273)
        S = convertChar(x);

Error in sym (line 229)
                S.s = tomupad(x);

Error in Newton_Raphson (line 6)
dif=diff(sym(a));

I can see that there are many who faced the same difficulty before, and I tried those solutions too like I tried using str2sym too but it throws the same kind of error on the line containing differential. Am I missing something? I am totally new in MATLAB world.

Questioner
Kanchan Bharti
Viewed
0
MichaelTr7 2020-11-28 08:55:59

Using the functions str2func(), sym() and matlabFunction() will allow you to convert the arguments to the appropriate input types required for the diff() function. Below is a little test/playground script that takes an anonymous function indicated by the @() indicating the dependent variables/input variables.

str2func(): Converts from stringanonymous function (function handle)
sym(): Converts from anonymous function (function handle)symbolic function
matlabFunction: Converts from symbolic functionanonymous function (function handle)

Input Arguments and Output Results

a = input('Enter function with right hand side zero:','s');

f = str2func(a);
dif = diff(sym(f));
d = matlabFunction(dif);

%Testing that the function handles (anonymous functions) work%
f(5)
d(2)

Ran using MATLAB R2019b