Problem with a function: "??? Undefined function or variable 'x'"

1 次查看(过去 30 天)
I'm trying to write a generic algorithm to use the Newton-Raphson method of finding the roots of a function, but my algorithm is having troubles with the call function system, giving the error: ??? Undefined function or variable 'x'.
Here's my algorithm, it doesn't have mistakes, because when I try to substitute the f, x and tol variables without calling the function it works perfectly.
function [x,y,err]=raphson(f,a,tol)
%syms x
%f=2*x.^3+log(x)-5
%a=2
%tol=10^-7
syms x
f1=diff(f);
x=a;
err=1;
while err>tol;
y=subs(f,x);
y1=subs(f1,x);
xk1=x-(y/y1);
err=y;
x=xk1;
end
end
The comentaries in the beginning of the algorythm are my attempts to atribute a value to the variables without using the function. I've tried everything and I can't get it to work.

回答(1 个)

Chaya N
Chaya N 2016-10-20
The input argument f is a symbolic expression. You are probably seeing the error because the variable x has not been defined as a symbolic variable before calling your function. Simply declare syms x before calling your function and it should work.

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by