Codice MATLAB
A=[ 6 2; 2 3]; C=[ -5 0]; epsilon1=10^-5; epsilon2=10^-5; epsilon3=10^-5; XO=[ 15 -10.3]'; a=1; b=1; c=1; k=0; x=XO; Xit=x';
while(a>epsilon1 | b>epsilon2 | c>epsilon3) k=k+1; gradF=A*x+c; a=norm(gradF); d=-gradF; alfa=-gradF'*d/(d'*A*d); x_new=x+alfa*d; f=1/2*x'*A*x+c'*x; f_new=1/2*x_new'*A*x_new+c'*x_new; b=norm(x_new-x)/max(norm(x),1); c=norm(f_new-f)/max(norm(f),1); x=x_new; Xit=[ Xit; x_new']; end
x=linspace(-20,20,300); y=linspace(-20,20,300); [X_graf,Y_graf]=meshgrid(x,y); Z_graf=3*X_graf.^2+2*X_graf.*Y_graf+3/2*Y_graf.^2-5*X_graf;
grid subplot(1,1,1); contour(X_graf,Y_graf,Z_graf,50); xlabel('x'); ylabel('y'); title('linee di livello di una funzione quadratica'); hold on
plot(Xit(:,1),Xit(:,2),'o'); plot(Xit(:,1),Xit(:,2)); hold off