My QR-decomposition code returns transpose of MATLABs Q, why?

clear
clc
%Create random integer dimensions m and n
m=randi(100);
n=randi(100);
%Create A of random integer dimensions m and n
A = randn(m,n);
%Assign A to A1 for calculation of relative error in the end
A1=A;
%Assign identity matrix to Q for the very first orthogonal transformation
Q=eye(m);
%Compute smallest dimension. This number will be en number of iterations of
%the loop
mindim=min(m-1,n);
%MATLABs Q and R, use for comparison
[Q1,R1]=qr(A);
for j=1:mindim
[v,tau] = gallery('house',A(j:end,j));
l=length(v);
Z = (eye(length(v)) - tau*(v*v'))';
block = [eye(j-1) zeros(j-1,l); zeros(j-1,l)' Z];
%Multiplying all reflections Q
Q=block'*Q;
%Multiplying all transformations of
A = block'*A;
end
%Q=Q';
R=A;
%Check and see if relative error is small, on the order of E-15.
relerr = norm(A1-Q*R) / norm(A1);
I have a script that takes in any matrix A and should return the factors Q and R of the QR-decomposition. R is created just fine, but my Q is different from MATLABs Q (Q1 in my code) in that it is the transpose of MATLABs Q. Why is this? I have tried finding an explanation but failed. Can anyone explain this to me?

4 Comments

Why is this?
It's because you constructed the transpose of Q (which is the same as the inverse of Q), i.e. a matrix Q such that Q.'*R = inv(Q)*R = A.
I think you should not expect that we check your algorithm to construct Q and R to find the reason for this.
Thank you. I had a feeling I was doing this even though I thought I was constructing Q. I cannot see that I am constructing Q still but I will have another look. I thought that maybe I was making an obvious mistake somewhere that was easy to spot. I dont expect anyone to go through my code in detail, unless they want to. I appreciate any help, no matter how detailed.
Since we know what the result must be, the change of
Q=block'*Q;
to
Q = Q*block;
gives the correct Q.
But don't ask me why.
Ah of course! I am so sloppy. Thank you!

Sign in to comment.

Answers (0)

Categories

Products

Release

R2020b

Asked:

on 11 Sep 2022

Commented:

on 11 Sep 2022

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!