function exempel7_5Newton() close all clear all f = @(x) cos(x)+x.^2-0.4*x; %Newtons metod fPrim = @(x) -sin(x)+2*x-0.4; fBis = @(x) -cos(x)+2; iter = 7; x = zeros(iter+1,1); x(1) = 0.5;%startapprox for n=1:iter x(n+1) = x(n) -fPrim(x(n))/fBis(x(n)); end %visualization xMesh = linspace(0,1)'; subplot(1,2,1); plot(xMesh,f(xMesh)); title('f(x)') xlabel('x') hold on subplot(1,2,2); plot(xMesh,fPrim(xMesh)); title('df/dx') xlabel('x') hold on format long for n=1:iter-1 subplot(1,2,1) plot(x(n),f(x(n)),'ko') title(['f(x_', num2str(n-1),')=',num2str(f(x(n)),'%10.8e\n')]) subplot(1,2,2) text(x(n),-0.05,['x_' num2str(n-1)]); plot([x(n) x(n)],[0 fPrim(x(n))],'-ko','linewidth',1); title(['df/dx, x_', num2str(n-1),'=',num2str(x(n),'%10.8e\n')]) pause(1) plot([x(n) x(n+1)],[fPrim(x(n)) 0],'-ko','linewidth',1); end disp('Newtons metod x f(x)') disp([x f(x)]) fminBndSolx = fminbnd(f,0,1)%,optimset('TolX',1e-15,'Display','off')) %builtIn matlab function for computing argmin_x f(x) end