Newton's method problem
Mostrar comentarios más antiguos
clear all; close all;
a=4;
b=3;
x=zeros();
x(1)=1;
for i=1:1000;
f(x(i))=(x(i)-a)^2+b;
x(i+1) =x(i)-(f(x(i))/diff(f(x(i))));
end
4 comentarios
Grzegorz Knor
el 7 de Oct. de 2011
Could you describe a problem that you try to solve using this code?
Andrei Bobrov
el 7 de Oct. de 2011
Hi Grzegorz! This is method Newton?
Prozka
el 7 de Oct. de 2011
Walter Roberson
el 7 de Oct. de 2011
Code that has a "clear all" statement is broken 99 times out of 100.
Respuestas (3)
Andrei Bobrov
el 7 de Oct. de 2011
for your case EDITED
f = @(x)(x - 4)^2 + 9;
syms x
ex = (x - 4)^2 + 9;
cf = double(coeffs(ex));
distxp = (4*prod(cf([1 end]))-cf(2)^2)/4/cf(3);
fun = matlabFunction(ex - distxp);
df = matlabFunction(diff(ex));
x = 10;
xout = x;
while abs(fun(x)) > 1e-6
x1 = x - fun(x)/df(x);
x = x1;
xout = [xout;x];
end
ADD corrected
f = @(x)(x - 4)^2 + 9;
syms x
ex = (x - 4)^2 + 9;
cf = fliplr(double(coeffs(expand(ex))));
distxp = (4*prod(cf([1 end]))-cf(2)^2)/4/cf(1);
fun = @(x)f(x)-distxp;
dcf = polyder(cf);
df = @(x)polyval(dcf,x);
x = 10;
xout = x;
while abs(fun(x)) > 1e-6
x1 = x - fun(x)/df(x);
x = x1;
xout = [xout;x];
end
output for the first 10 iterations and optimal x
if numel(xout)<=10
out = xout;
else
out = [xout(1:10);xout(end)];
end
7 comentarios
Prozka
el 7 de Oct. de 2011
Prozka
el 9 de Oct. de 2011
Andrei Bobrov
el 9 de Oct. de 2011
corrected
Prozka
el 9 de Oct. de 2011
Andrei Bobrov
el 9 de Oct. de 2011
outf = f(out(end))
Andrei Bobrov
el 9 de Oct. de 2011
Proshka, include your head (brain) 10000 iterations is very many
Prozka
el 9 de Oct. de 2011
Andreas Goser
el 7 de Oct. de 2011
0 votos
This code isn't working because diff(f(x(i))) returns [] and thus a scalar can't be divide by [].
1 comentario
Prozka
el 7 de Oct. de 2011
Steve
el 9 de Oct. de 2011
You can use this Newton function implementation in general.
function n = newton(f,fp,x0,tol,Nmax)
n=0;
test_val = abs(poly_val(f,x0));
num1 = 1;
while (test_val > tol && num1<Nmax)
n = x0 - poly_val(f,x0)/poly_val(fp,x0);
test_val = abs(poly_val(f,n));
x0=n;
num1=num1+1;
end
end
1 comentario
Prozka
el 9 de Oct. de 2011
Categorías
Más información sobre Nonlinear Optimization en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!