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.
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 string → anonymous function (function handle)
• sym()
: Converts from anonymous function (function handle) → symbolic function
• matlabFunction:
Converts from symbolic function → anonymous function (function handle)
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
Thank you so much! That worked.
No problem, Glad it worked!!! :)