Need with help with error on Newton's Method function

3 ビュー (過去 30 日間)
Quresh
Quresh 2015 年 2 月 8 日
回答済み: Erik S. 2015 年 2 月 8 日
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)

回答 (1 件)

Erik S.
Erik S. 2015 年 2 月 8 日
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

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by