I got an error of my code. This code is Newton's method. Can anybody help with me?? Thank you!!

error occur: Newton (line 3)
[x,y] = Newton(f, df, 0.5, 0.00001, 5);
f = inline('x.^3-3*x.^2+4/3');
df = inline('3*x.^2-6*x');
[x,y] = Newton(f, df, 0.5, 0.00001, 5);
% function [x, y] = Newton(fun, funpr, x1, tol, kmax)
% Input:
% fun function (inline function or m-file function)
% funpr derivative function (inline or m-file)
% x1 starting estimate
% tol allowable tolerance in computed zero
% kmax maximum number of iterations
%output
% x (row) vector of approximations to zero
% y (row) vector fun(x)
x(1)= x1;
y(1) = feval(fun, x(1));
ypr(1) = feval(funpr, x(1));
for k = 2: kmax
x(k) = x(k-1)-y(k-1)/ypr(k-1); y(k) = feval(fun, x(k));
if abs(x(k)-x(k- 1)) <tol
disp('Newton method has converged?'); break;
end
ypr(k) = feval(funpr, x(k));
iterk;
end
if (iter >= kmax)
disp('zero not found to desired tolerance');
end
n = length(x);
k = 1:n;
out = [k' X' y'];
disp(' step x y')
disp(out)

Antworten (1)

Put the lines
f = inline('x.^3-3*x.^2+4/3');
df = inline('3*x.^2-6*x');
[x,y] = Newton(f, df, 0.5, 0.00001, 5);
into a file named Newton_test.m
Then in Newton.m have the rest of your code with the 'function' line not commented out.
function [x, y] = Newton(fun, funpr, x1, tol, kmax)
% Input:
% fun function (inline function or m-file function)
% funpr derivative function (inline or m-file)
% x1 starting estimate
% tol allowable tolerance in computed zero
% kmax maximum number of iterations
%output
% x (row) vector of approximations to zero
% y (row) vector fun(x)
x(1)= x1;
y(1) = feval(fun, x(1));
ypr(1) = feval(funpr, x(1));
for k = 2: kmax
x(k) = x(k-1)-y(k-1)/ypr(k-1); y(k) = feval(fun, x(k));
if abs(x(k)-x(k- 1)) <tol
disp('Newton method has converged?'); break;
end
ypr(k) = feval(funpr, x(k));
iterk;
end
if (iter >= kmax)
disp('zero not found to desired tolerance');
end
n = length(x);
k = 1:n;
out = [k' X' y'];
disp(' step x y')
disp(out)
And to run this you would execute the file Newton_test

2 Kommentare

I followed your instruction, but there is an error again. Can you give me more specific solution? Thank you very much!!
You need to tell us what the error message is and show us exactly where it is occurring.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Function Creation finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 28 Sep. 2015

Kommentiert:

am 28 Sep. 2015

Community Treasure Hunt

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

Start Hunting!

Translated by