Skip to content

Instantly share code, notes, and snippets.

@hyiltiz
Created January 21, 2024 08:23
Show Gist options
  • Save hyiltiz/57d27bc638b1cd2b982931d10993de80 to your computer and use it in GitHub Desktop.
Save hyiltiz/57d27bc638b1cd2b982931d10993de80 to your computer and use it in GitHub Desktop.
Simple QR decomposition and SVD in Octave
function qr_decomp()
Qs = cell();
m0 = reshape(1:9, [3, 3])'
m = m0;
k = 0;
[Q, Qm] = qr1(m);
Q = [eye(k) zeros([k size(m, 2)]);
zeros([size(m, 1) k]) Q];
Qs{1} = Q;
% --------- step 2
k = 1;
m = Qm(2:end, 2:end)
[Q, Qm] = qr1(m);
Q = [eye(k) zeros([k size(m, 2)]);
zeros([size(m, 1) k]) Q];
Qs{2} = Q;
% ----- compare results
[oQ, oR] = qr(m0)
Q = Qs{1} * Qs{2}
R = Qs{2} * Qs{1} * m0
Q * R
Qs
end
function [Q, Qm] = qr1(m)
x = m(:,1);
e1 = zeros([numel(x) 1]);
e1(1) = 1;
a = -1 * norm(x);
u = x - a * e1;
v = u / norm(u);
Q = eye(numel(v)) - 2 * v * v';
Qx = Q*x;
Qm = Q*m;
end
k = 99;
A = rand(k);
A = reshape(1:9, [3 3]);
QRs = cell();
N = 100; % number of iterations
R1 = A;
U = eye(size(A));
V = eye(size(A));
for i = 1 : N
[Q1, R1] = qr(R1);
[Q2, R2] = qr(R1');
R1 = R2';
U = U * Q1;
V = V * Q2;
% QRs{i} = {Q1, R1, Q2, R2, U, V};
end
S = R1;
figure; for i=1:numel(QRs); imshow(QRs{i}{2}, [-5, 5]); title(num2str(i)); colormap gray; pause(0.2); end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment