feat: beautifying QRDecomposition.m

This commit is contained in:
PolishPigeon 2022-01-07 20:18:31 +01:00
parent 86d22f87a9
commit c7e5df2bcc

View File

@ -1,26 +1,37 @@
function [Q, R, invqtq] = QRDecomposition(A) function [Q, R, QTQInverse] = QRDecomposition(A)
% initialize empty matrices [Q, R, QTQInverse, upperLoopLimit] = initialize(A);
Q = zeros(size(A)); [Q, R, QTQInverse] = GramSchmidtAlgorithm(A, Q, R, QTQInverse, upperLoopLimit);
R = eye(size(A, 2)); end
invqtq = zeros(size(A, 2));
function [Q, R, QTQInverse, upperLoopLimit] = initialize(Matrix)
% modified Gram-Schmidt, use each column to orthogonalize the ones in front of it Q = zeros(size(Matrix));
for col = 1:size(A, 2) upperLoopLimit = size(Matrix, 2);
% by the time we've reached this column, it's already been orthogonalized R = eye(upperLoopLimit);
Q(:, col) = A(:, col); QTQInverse = zeros(upperLoopLimit);
end
% calculate current column dot product for R
coldot = dot(Q(:, col), Q(:, col)); function [Q, R, QTQInverse] = GramSchmidtAlgorithm(A, Q, R, QTQInverse, upperLoopLimit)
invqtq(col, col) = 1 / coldot; for column = 1 : upperLoopLimit
[Q, R, QTQInverse, A] = GramSchmidtAlgorithmOuterLoop(upperLoopLimit, A, Q, R, QTQInverse, column);
% orthogonalize further columns end
for next = (col + 1):size(A, 2) end
% calculate R cell for this column pair
R(col, next) = dot(Q(:, col), A(:, next)) / coldot; function [Q, R, QTQInverse, A] = GramSchmidtAlgorithmOuterLoop(upperLoopLimit, A, Q, R, QTQInverse, column)
% orthogonalize column [columnDotProduct, QTQInverse, Q] = calculateColumnDotProduct(A, column, Q, QTQInverse);
A(:, next) = A(:, next) - R(col, next) * Q(:, col); [R, A] = orthogonalizeFurther(column, A, columnDotProduct, Q, R, upperLoopLimit);
end end
end
function [columnDotProduct, QTQInverse, Q] = calculateColumnDotProduct(A, column, Q, QTQInverse)
Q(:, column) = A(:, column);
columnDotProduct = dot(Q(:, column), Q(:, column));
QTQInverse(column, column) = 1 / columnDotProduct;
end
function [R, A] = orthogonalizeFurther(column, A, columnDotProduct, Q, R, upperLoopLimit)
for next = (column + 1): upperLoopLimit
R(column, next) = dot(Q(:, column), A(:, next)) / columnDotProduct;
A(:, next) = A(:, next) - R(column, next) * Q(:, column);
end
end end