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

1 view (last 30 days)
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.

Answers (1)

Chaya N
Chaya N on 20 Oct 2016
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.

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!