function cgmE

%  check CGM for solving Ax=b and
%  compare different error measures

% matrix A from solving Laplace's equation
N=40;
M=N;
n=N*M;
lambda2=1;
D=2*(1+lambda2)*eye(n,n);
SD1=diag(-lambda2*ones(n-1,1),-1);
for i=N+1:N:n-1
    SD1(i,i-1)=0;
end
SDM=diag(-ones(n-M,1),-M);
A=D+SD1+SD1'+SDM+SDM';
cond_of_A=cond(A,inf)

% specify solution (xe)
sol=2*(1-0.5*rand(n,1));
b=A*sol;

fprintf('\n n = %i \n\n',n)

tol=1e-12;
x=zeros(n,1);
% start iteration
r=b-A*x;
d=r;
rr=r'*r;
err=10*tol;
counter=0;
while err>tol
    counter=counter+1;
    q=A*d;
    alpha=rr/(d'*q);
    x=x+alpha*d;
    r=r-alpha*q;
    rr0=rr;
    rr=r'*r;
    beta=rr/rr0;
    d=r+beta*d;
    iter(counter)=counter;
    error2(counter)=norm(alpha*d,inf);
    error3(counter)=norm(r,inf);
    error(counter)=norm(x-sol,inf);
    err=error2(counter);
end

clf
% get(gcf)
set(gcf,'Position', [25 1115 658 230])
co = [0 0 1;
    0 0.5 0;
    1 0 0;
    0 0.75 0.75;
    0.75 0 0.75;
    0.75 0.75 0;
    0.25 0.25 0.25];
set(groot,'defaultAxesColorOrder',co)

for ic=1:length(iter)
    clf
    loglog(iter(1:ic),error(1:ic),'-.k','LineWidth',2)
    axis([ 1 1000 1e-12 10])
    set(gca,'MinorGridLineStyle','none')
    set(gca,'YTick',[1e-12 1e-8 1e-4 1 ])
    hold on
    loglog(iter(1:ic),error2(1:ic),'-r','LineWidth',2)
    loglog(iter(1:ic),error3(1:ic),'--b','LineWidth',2)
    grid on  
    ylabel('Error')
    xlabel('Iteration Step')
    legend({' Error',' Iteration Error',' Residual'},'Location','SouthWest','FontSize',16,'FontWeight','bold')
    set(gca,'FontSize',16,'FontWeight','bold')
    
    pause(0.01)
    
end

















