function fig9_11

%  check CGM for solving Ax=b and
%  for poor converging matrix

% create symmetric matrix with specififed eigenvalues
n=100;
[Q,R]=qr(randn(n,n));
D=diag(logspace(0,6,n));  % log spacing
%D=diag(randi(10^6,1,n));  % random
%D=diag(linspace(1,10^6,n));  % uniform spacing
A=Q'*D*Q;

cond_A=cond(A,2)

% specify solution (xe)
xe=ones(n,1);
b=A*xe;

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

% use CGM to solve matrix equation
x=cgm(A,b,xe);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CGM
function x=cgm(A,b,sol)

% set CGM parameters
tol=1000*eps;

n=length(b);
x=zeros(n,1);
tic
% start iteration
r=b-A*x;
d=r;
rr=r'*r;
err=10*tol;
counter=0;
while err>tol && counter<10*n
    counter=counter+1;
    q=A*d;
    alpha=rr/(d'*q);
    bad=alpha*d;
    x=x+bad;
    r=r-alpha*q;
    rr0=rr;
    rr=r'*r;
    beta=rr/rr0;
    d=r+beta*d;
    steps(counter)=counter;
    error2(counter)=norm(bad,inf);
    error(counter)=norm(x-sol,inf);
    err=error2(counter);
end
cgm_time=toc;

fprintf('\n  Number of CGM Iterations = %i     Error =  %e    Time = %e \n\n',counter,error(counter),cgm_time)

clf
% get(gcf)
set(gcf,'Position', [25 1115 658 230])
subaxis(1,1,1,1,'MT',0.01,'MB',0.185,'MR',-0.02,'ML',0.06,'P',0.04)
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)

loglog(steps,error,'b','LineWidth',1.6)
hold on
loglog(steps,error2,'r','LineWidth',1.6)

grid on
set(gca,'MinorGridLineStyle','none')
axis([ 1 1000 1e-12 10])
set(gca,'YTick',[1e-12 1e-8 1e-4 1 ])
ylabel('Error')
xlabel('Iteration Steps (k)')
legend(' Error',' Iterative Error','Location','SouthWest','FontSize',16,'FontWeight','bold')
set(gca,'FontSize',16,'FontWeight','bold')
hold off

%exportgraphics(gcf,'/Users/mark/Desktop/nonconv.eps')

















