% inversio-ongelmien laskennallinen pk 2012
% harjoitus 3


A1 = [1 2 3;-1 0 2; 3 1 0];
A2 = [1 2 3;-1 2 1; 2 -3 1; 0 2 2];
A3 = [1 2 3; -1 2 1];
A4 = [1 2 3; -2 1 1; -1 3 4];


% Calculate the singular value decompositions
[u1,s1,v1] = svd(A1);
[u2,s2,v2] = svd(A2);
[u3,s3,v3] = svd(A3);
[u4,s4,v4] = svd(A4);


% Pseudoinverses using svd

% A1, invertible
pA1 = v1*inv(s1)*u1';

% A2, overdetermined, rank(A2) = 3
pA2 = v2(:,1:3)*inv(s2(1:3,1:3)) * u2(:,1:3)';

% A3, underdetermined, rank(A) = 2
pA3 = v3(:,1:2) * inv(s3(1:2,1:2)) * u3(:,1:2)';

% A4, degenerate matrix, rank = 2
pA4 = v4(:,1:2) * inv(s4(1:2,1:2)) * u4(:,1:2)';



% QR decompositions
[q1,r1] = qr(A1);
[q2,r2] = qr(A2);
[q3,r3] = qr(A3);
[q4,r4] = qr(A4);


% Pseudoinverses using QR decomposition

% A1, invertible, rank = 3
rr = r1(1:3,:);
pA11 = inv(rr) * q1';

% A2, overdetermined, rank = 3
rr = r2(1:3,:);
pA22 = inv(rr) * q2(:,1:3)';

% A3, underdetermined, rank = 2
rr = r3(1:2,:);
pA33 = pinv(rr) * q3(:,1:2)';

% A4, degenerate, rank = 2
rr = r4(1:2,:);
pA44 = pinv(rr) * q4(:,1:2)';