Newton's Method missing value
Afficher commentaires plus anciens
I wrote Newton's method to be
function [cVec,n] = Newtons_method(f,fp,x0,tol,nmax)
cVec = [];
cVec(1)=x0;
i=0;
while i <=nmax
i=i+1;
cVec(i)=x0;
c = x0-(f(x0)/fp(x0));
if abs(c-x0)<tol
c=x0;
break;
else
x0=c;
end
end
n=i-1;
cVec=cVec';
end
and used the following to call it
f=@(x)(x.^2-3);
fp=@(x)(2.*x);
x0=2;
tol=10^-10;
nmax= 100;
[c,n]=Newtons_method(f,fp,x0,tol,nmax)
From this, I get a [5,1] column vector but I'm supposed to get a [6,1] vector. I've messed around with the placement of certain lines of code and indices, but haven't gotten the desired result.
Thanks in advance.
Réponses (1)
If n is the number of Newton steps, you must start with n = 0 instead of n = 1 in "Newtons_method".
I counted the number of Newton steps + the initial value, thus the length of the array cVec.
f = @(x) x.^2-3;
fp = @(x) 2.*x;
x0 = 2;
tol = 10^-10;
nmax = 100;
format long
[c,n] = Newtons_method(f,fp,x0,tol,nmax)
function [cVec,n] = Newtons_method(f,fp,x0,tol,nmax)
cVec(1) = x0;
n = 1;
while n <= nmax
c = x0 - f(x0)/fp(x0);
n = n+1;
cVec = [cVec;c];
if abs(c-x0) < tol
break;
else
x0 = c;
end
end
end
Catégories
En savoir plus sur App Building dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!