How do I take input from a user (equation in terms of x) and convert it into an equation matlab would understand and use this to perform a differentiation in order to perform a newton-raphson method.

2 views (last 30 days)
function y=newtraph(varargin)
% newtraph: Newton-Raphson root location zeroes
% y=newtraph(varargin):
% uses Newton-Raphson method to find the root of func
% input:
% func = name of function
% dfunc = name of derivative of function
% xr = initial guess
% es = desired relative error (default = 0.0001)
% maxit = maximum allowable iterations (default = 50)
% p1,p2,... = additional parameters used by function
% output:
% root = real root
% ea = approximate relative error
% iter = number of iterations
xr=input('input initial guess: ');
func=input('input function in terms of x: ');
func=vectorize(char(func));
eval(['f = @(x) ' func]);
dfunc=diff(func,x,1);
es=0.0001;
maxit=20;
iter = 0;
while (1)
xrold = xr;
xr = xr - func(xr)/dfunc(xr);
iter = iter + 1;
if xr ~= 0, ea = abs((xr - xrold)/xr); end
if ea <= es iter >= maxit, break, end
end
root = xr;
display(root);
end
% this is the error message I keep getting:
% ??? Error using ==> input
% Undefined function or variable 'x'.
%Error in ==> newtraph at 18
% func=input('input function in terms of x: ');

Answers (1)

Sergio E. Obando
Sergio E. Obando on 1 Aug 2024
You could use something like this:
syms f(x)
xr=input('input initial guess: ');
func=input('input function in terms of x: ','s');
f(x) = str2sym(func)
dfunc=diff(f,x)
func = matlabFunction(f)
dfunc = matlabFunction(dfunc)
Otherwise, a numerical approach may look like this:
func = @(X) X.^2 - 4;
dfunc = @(X) 2*X;
nIter = 1000;
tol = 0.001;
x = zeros(1,nIter);
x(1) = 1;
for ii = 1:nIter
x(ii+1) = x(ii) - f(x(ii))/dfdx(x(ii));
if abs(f(x(ii+1))) < tol
disp(x(ii+1));
break
end
end

Community Treasure Hunt

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

Start Hunting!