I got an error of my code. This code is Newton's method. Can anybody help with me?? Thank you!!
조회 수: 13 (최근 30일)
이전 댓글 표시
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)
댓글 수: 0
답변 (1개)
Walter Roberson
2015년 9월 28일
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
Walter Roberson
2015년 9월 28일
You need to tell us what the error message is and show us exactly where it is occurring.
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!