n = 5;
A = diag(-1*ones(n-1,1),-1) + diag(1*ones(n,1)); 
A = A+A';

lam = eig(A);

% simultaneous iteration
Q = eye(size(A));
for i = 1:100
    Z = A*Q;
    [Q R] = qr(Z); % orthonormalization    
    err(i) = norm(sort(diag(Q'*A*Q)) - sort(lam));
end

% QR iteration
for i = 1:100
    [Q R] = qr(A);
    A = R*Q;  
    errQR(i) = norm(sort(diag(A)) - sort(lam));
end

semilogy(err,'bx-','linewidth',2)
hold on
semilogy(errQR,'ro-','linewidth',2)

%% QR iteration

Ak = A;
I = eye(n);
Qtilde = I;
for i = 1:50
    [Qk Rk] = qr(Ak);
    Ak = Rk*Qk; 
    Qtilde = Qtilde*Qk; % Q1*Q2*Q3*...*Qk
    norm(sort(diag(Ak))-sort(lam))
end
% norm(sort(diag(Ak))-sort(lam))

% compare QR and SI eigvals
[sort(diag(Q'*A*Q)) - sort(lam),sort(diag(Ak))-sort(lam)]

% compare Q,Qtilde
Q,Qtilde