Least squares in julia

Hello, good afternoon,

I’m facing issues to solve least squares in julia using qr decomposition.

numcourses = [13,4,12,3,14,13,12,9,11,7,13,11,9,2,5,7,10,0,9,7]
happiness  = [70,25,54,21,80,68,84,62,57,40,60,64,45,38,51,52,58,21,75,70]

X = [ones(length(numcourses)) numcourses]
F = qr(X)

beta = inv(F.R) * (F.Q' * happiness)

The inv(F.R) is 2x2 matrix anf fails to multiply the result of F.Q * happiness.

Same code in python works as expected and I had checked vector and matrices sizes. Hadamard and broadcast cant be used also

beta = np.linalg.inv(R) @ (Q.T@happiness)

Just do X \ happiness the correct thing using a qr factorization will be done for you automatically.

5 Likes

yes, it works, but the focus is to use qr in exercise. Cant understand the python black magic here. Understood that a 2x2 matrix cant multiply a 20x1 column vector

You might have to call Matrix(F.Q), also, I’m not sure, but there might be a full keyword argument you could use to qr

1 Like

that worked but I dont understood why. May you please explain ?

Before, Q was a 20x20 and after the cast, was 20x2.

I think it’s described in the docstring for qr and the associated factorization type

1 Like

I think I understood the docstrings, but it is not so clear. The docs mention the result of qr are store in compact form, and it makes sense to cast to a Matrix. Thank you.