Need with help with error on Newton's Method function

3 views (last 30 days)
function [ ] = newton(f,fprime,x0,tol)
x(1) = x0 - (f(x0)/fprime(x0));
error(1) = abs(x(1)-x0);
k=2;
while (error(k-1)) >= tol
x(k)= x(k-1) - (f(x(k-1))/fprime(x(k-1)));
error(k)= abs(x(k)-x(k-1));
k=k+1;
end
fprintf('Errors\n')
disp(error)
fprintf('Iteration values\n')
disp(x)
fprintf('The root is %d',x(end))
end
Above is a function I built for a simple lab for class where I have to build Newton's method into a function. We have to solve for the below function; however, when I run it I receive the following error:
>> syms x
>> f=(x^2)+(exp(-x)*cos(x));
>> a=diff(f)
a =
2*x - exp(-x)*cos(x) - exp(-x)*sin(x)
>> x0=-2.5;
>> tol=1e-5;
>> newton(f,a,x0,tol)
Error using sym>checkindex (line 2248)
Index must be a positive integer or logical.
Error in sym>privformatscalar (line 2198)
checkindex(x);
Error in sym>privformat (line 2182)
s = privformatscalar(x);
Error in sym/subsref (line 1387)
[inds{k},refs{k}] = privformat(inds{k});
Error in newton (line 3)
x(1) = x0 - (f(x0)/fprime(x0));
Can anyone help me figure out what I'm doing wrong? Sorry for the probably very simple question, I'm just new to coding and am not the best at this so I'm struggling to understand even what the error is about.
(Also, the parameters I used for x0 and tol are the ones requested by the lab instructor)

Answers (1)

Erik S.
Erik S. on 8 Feb 2015
Hi,
You cannot pass a symbolic variable to your functions in that way. Since you have you function and its derivative you can write the code like the following and pass the function newton values x0 and tol:
function [ ] = newton(x0,tol)
x(1) = x0 - (f(x0)/fprime(x0)); error(1) = abs(x(1)-x0); k=2;
while (error(k-1)) >= tol
x(k)= x(k-1) - (f(x(k-1))/fprime(x(k-1)));
error(k)= abs(x(k)-x(k-1));
k=k+1;
end
fprintf('Errors\n') disp(error) fprintf('Iteration values\n') disp(x) fprintf('The root is %d',x(end))
end
% Function function y = f(x) y = x.^2 + (exp(-x)*cos(x)); end
% Derivative function dy = fprime(x) dy = 2*x - exp(-x)*cos(x) - exp(-x)*sin(x); end

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!