I have to program the qr iteration for the university and compare it with the commands eigvals and eigvecs. Unfortunately I can’t get the code to output the correct and same vectors as eigvecs. eigvecs gives me a complex vector and the Qr algorithm only a real number. Can someone maybe help me with this? Or are there certain matrix defaults why the qr code does not work?

Thanks in advance

My code:
using LinearAlgebra
using BenchmarkTools

function qr_algorithm(matrix)
A = copy(matrix)
eigenvalues =
eigenvectors = Matrix{Float64}(I, size(A, 1), size(A, 2))

for k = 1:1000
Q, R = qr(A)
A = R * Q
eigenvalues = diag(A)
if norm(diag(A, 1), 2) < 1e-6
break
end
eigenvectors *= Q
end
eigenvalues, eigenvectors

If this is a homework assignment, I’m not sure what sort of help is appropriate. An explicit unshifted QR iteration like this is not what is normally considered a practical QR iteration. But it doing this sort thing is instructional when learning about the properties of the QR iteration.

I have assigned this sort of thing before and would not want my students getting overly specific help on the internet. But even for homework , it seems reasonable to give you two general things to consider that I think you’ll need to look at if you want to understand what’s going on. Both of them relate to the fact that you need to look more closely at what the QR iteration is supposed to do to the matrix A:

In the convergence criteria you are using, you are looking only at the first superdiagonal. This is sufficient if the matrix is symmetric tridiagonal, but not in general. As it is, your termination condition doesn’t do anything and both examples run for 1000 iterations.

You might want to note that you appear to be getting the real eigenvalues, just not the conjugate pairs of eigenvalues. You should look up what the QR iteration does to a real, non-symmetric matrix. Specifically, it does not in general have all the eigenvalues on the diagonal of A. A good search term is the “real Schur decomposition.” Not all books in numerical linear algebra cover this. The popular book by Trefethen and Bau focuses on the symmetric/Hermitian case.