Question

I'm trying to write a program that gets an mxn matrix and QR decomposes it.

It's not finished yet, but I've encountered a problem. I've tried running my program with the example shown at wikipedia http://en.wikipedia.org/wiki/QR_decomposition

A=[12,-51,4;6,167,-68;-4,24,-41]

What they called Q1, Q2...I called Qtemp. and everytime i calculate Qtemp, i print it in order to see that I get same result as wikipedia. For Q1 I do, but for Q2 I don't.

Their Q2 and mine are of the same value, but different signs. where they have a + i have a -, where they have a -, i have a +.

this is my code:

    Q=eye(m);
R=A;
for i=1:min(m-1,n)
    ei=zeros(n,1);
    ei(i,1)=1;
    x=A(:,i);
    for j=1:i-1
        x(j,1)=0;
    end
    u=x-norm(x)*ei;
    v=u/norm(u);
    Qtemp=eye(m)-2*(v*v');
    A=Qtemp*A;
    disp(Qtemp);
end

I literally just copied their algorithm and translated it to code, but still bad output for second Qtemp.

Was it helpful?

Solution

It looks like you're not reducing the size of the blocks on each iteration. Everything seems to be a function of the same m and n (which you didn't define in your code). See the line on the Wikipedia page where they define A′ and use it to build Q2 (just the lower two thirds). Below is some code of mine adapted to perform QR-decomposition of 3-by-3 matrices that might help. Note particularly that the second block only works on A(:,2) and q(2:3,:):

function [q,r]=qr3(A)

u = A(:,1);
u(1) = u(1)-(1-2*(u(1)<0))*norm(u); % Flip < to > to match sign convention of qr
u = u/norm(u);
u(~isfinite(u)) = sqrt(3)/3;
q = -2*(u*u');
q([1 5 9]) = q([1 5 9])+1;

u = q(2:3,:)*A(:,2);
u(1) = u(1)-(1-2*(u(1)<0))*norm(u); % Flip < to > to match sign convention of qr
u = u/norm(u);
u(~isfinite(u)) = sqrt(2)/2;
q(:,2:3) = q(:,2:3)*[1-2*u(1)^2 -2*u(1)*u(2);
                     -2*u(1)*u(2) 1-2*u(2)^2];
r = triu(q'*A);

The above code and the method detailed on Wikipedia use a different sign convention from Matlab's qr function. See my comments in the code for how to flip the sign.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top