%% Main script
type konj_tab.m
disp('');disp('Konjugovane gradienty - Polak a Ribiere');format short e;%clc;
clear;close all
c=input('Vychodiskovy bod x0 = ');d=input('Presnost delta =');x(1,:)=c;o=1;m=0;hold on;
[fl,ql]=e9(c);
g(1,:)=ql;s(1,:)=g(1,:);
while (g(o,:)*g(o,:)'>d)&(o<44),
i=1; ml=0;
jl=-s(o,:)*ql';S=-sign(jl);
mp=S*d;
e=c-S*d*s(o,:);
[fp,q]=e9(e);
jp=-s(o,:)*q';
while jl*jp>0,
jl=jp;fl=fp;ml=mp;
mp=ml+S*d*2^i;
e=c-mp*s(o,:);
[fp,q]=e9(e);
jp=-s(o,:)*q';
i=i+1;
end
if S<0,
jo=jp;jp=jl;jl=jo;
fo=fp;fp=fl;fl=fo;
mo=mp;mp=ml;ml=mo;
end
j=min([jp,-jl]);
while j*j>.01*d*d,
z=jp+jl-3*(fp-fl)/(mp-ml);w=sqrt(z*z-jp*jl);
m=ml+(mp-ml)*(z+w-jl)/(jp-jl+2*w);
e=c-m*s(o,:);
[f,q]=e9(e);j=-s(o,:)*q';
if j>0,
fp=f;jp=j;mp=m;
else
fl=f;jl=j;ml=m;
end
end
x(o+1,:)=x(o,:)-m*s(o,:);o=o+1;c=x(o,:);
[fl,ql]=e9(c);
g(o,:)=ql;
k(o-1)=g(o,:)*(g(o-1,:)-g(o,:))'/(g(o-1,:)*g(o-1,:)');
s(o,:)=g(o,:)-k(o-1)*s(o-1,:);
gm(o-1)=m;
end;
% kreslenie obrazka
[X,Y] = meshgrid(-1:.1:2, -1:.1:2);
Z = X.^4+5*Y.^2-X.*Y-2*Y;
% vykreslenie vrstevnic do dalsieho obrazka
v=-0.2:.1:20;vc=v.*v;
contour(X,Y,Z,v)
hold on
title('Metรณda konjug. gradientov')
roz=size(x);
a=x(:,1);b=x(:,2);
for i=1:roz(1)-1
P2=plot([a(i),a(i+1)],[b(i),b(i+1)],'g',[a(i),a(i+1)],[b(i),b(i+1)],'ok');
set(P2,'linewidth',2);
pause(0.3)
end
P2=plot(a,b,'g',a,b,'ok');
hold off
u=g(:,1);v=g(:,2);p=s(:,1);n=s(:,2);w=floor(o/22);
x1=a;x2=b;g1=u;g2=v;s1=p;s2=n;
Vysledky=table(x1,x2,g1,g2,s1,s2)
krokov=roz(1)-1
%% Function file
type e9.m
function [p,q]=e9(x)
% x1^2+x2^2-4x1-5x2-5
% p=x(1)^2/4+x(2)^2/9-0.8*x(1)-x(2)-0.3*x(1)*x(2)-3;
% q(1)=0.5*x(1)-.8-0.3*x(2);
% q(2)=2*x(2)/9-1-0.3*x(1);
%x^4+5*y^2-x*y-2*y
p=x(1)^4+5*x(2)^2-x(1)*x(2)-2*x(2);
q(1)=4*x(1)^3-x(2);
q(2)=10*x(2)-x(1)-2;