Problem with Newton-Rapshon code

1 次查看(过去 30 天)
So I have this simple code:
function y=divsin(fun,xo,tol)
dfun=diff(sym(fun));
f=subs(fun,xo);
df=subs(dfun,xo);
c=1;
while abs(f)>tol
a=xo-f/df;
f=subs(fun,a);
df=subs(dfun,a);
xo=a;
c=c+1;
end
c
a
I need help to find out my mistake. This is what I get when I execute it:
divsin('x^2-2',1,0.0001)
Error using sym>convertChar (line 1459)
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 1225)
S = convertChar(x);
Error in sym (line 214)
S.s = tomupad(x);
Error in divsin (line 3)
dfun=diff(sym(fun));

回答(1 个)

Areej Varamban Kallan
编辑:Areej Varamban Kallan 2019-2-7
Hi Diego,
In your code, you are passing a character array to 'sym', this is not correct. Add the following line after function definition.
fun = evalin(symengine,fun);
Change the defintion of dfun to:
dfun = diff(fun);

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by