2021-03-13 13:42:56 +01:00
|
|
|
|
function [P, Q, L, U] = Alg2_gaussian_elimination_with_complete_pivoting(A)
|
2021-03-13 20:23:23 +01:00
|
|
|
|
% Algorithm 2: Gaussian Elimination with Complete Pivoting.
|
2021-03-14 18:40:53 +01:00
|
|
|
|
% [P, Q, L, U] = Alg2_gaussian_elimination_with_complete_pivoting(A)
|
|
|
|
|
% computes the complete pivoting factorization PAQ = LU.
|
2021-03-06 15:54:10 +01:00
|
|
|
|
|
2021-03-14 18:40:53 +01:00
|
|
|
|
[m, n] = size(A);
|
2021-03-13 20:23:23 +01:00
|
|
|
|
|
2021-03-14 18:40:53 +01:00
|
|
|
|
if m ~= n
|
|
|
|
|
error('Matrix is not square!')
|
2021-03-06 15:54:10 +01:00
|
|
|
|
end
|
|
|
|
|
|
2021-03-14 18:40:53 +01:00
|
|
|
|
% p and q are permutation vectors – respectively rows and columns
|
|
|
|
|
p = 1:m;
|
|
|
|
|
q = 1:m;
|
2021-03-06 20:58:15 +01:00
|
|
|
|
|
2021-03-14 18:40:53 +01:00
|
|
|
|
% The following algorithm is based on the Algrotihm 3.4.2 from [2].
|
|
|
|
|
|
|
|
|
|
for k = 1 : m-1
|
|
|
|
|
i = k:m;
|
|
|
|
|
j = k:m;
|
|
|
|
|
% Find the maximum entry to be the next pivot
|
2021-03-06 20:58:15 +01:00
|
|
|
|
[max_val, rows_of_max_in_col] = max(abs(A(i, j)));
|
2021-03-13 20:23:23 +01:00
|
|
|
|
[~, max_col] = max(max_val);
|
2021-03-06 20:58:15 +01:00
|
|
|
|
max_row = rows_of_max_in_col(max_col);
|
2021-03-14 18:40:53 +01:00
|
|
|
|
% Assign value of mu and lambda in respect to the main matrix A
|
2021-03-07 22:56:18 +01:00
|
|
|
|
[mi, lm] = deal(max_row+k-1, max_col+k-1);
|
2021-03-14 18:40:53 +01:00
|
|
|
|
% Interchange the rows and columns of matrix A...
|
|
|
|
|
A([k mi], 1:m) = deal(A([mi k], 1:m));
|
|
|
|
|
A(1:m, [k lm]) = deal(A(1:m, [lm k]));
|
|
|
|
|
% ...and respective permutation vectors entries.
|
2021-03-07 22:56:18 +01:00
|
|
|
|
p([k, mi]) = p([mi, k]);
|
|
|
|
|
q([k, lm]) = q([lm, k]);
|
|
|
|
|
% Perform Gaussian elimination with the greatest pivot
|
2021-03-06 15:54:10 +01:00
|
|
|
|
if A(k, k) ~= 0
|
2021-03-14 18:40:53 +01:00
|
|
|
|
rows = k+1 : m;
|
2021-03-06 18:17:36 +01:00
|
|
|
|
A(rows, k) = A(rows, k)/A(k, k);
|
|
|
|
|
A(rows, rows) = A(rows, rows) - A(rows, k) * A(k, rows);
|
2021-03-06 15:54:10 +01:00
|
|
|
|
end
|
2021-03-06 18:17:36 +01:00
|
|
|
|
end
|
2021-03-06 20:58:15 +01:00
|
|
|
|
|
2021-03-14 18:40:53 +01:00
|
|
|
|
I = eye(m);
|
2021-03-13 20:23:23 +01:00
|
|
|
|
U = triu(A);
|
|
|
|
|
L = tril(A, -1) + I;
|
2021-03-07 22:56:18 +01:00
|
|
|
|
P = I(p, :);
|
2021-03-14 18:40:53 +01:00
|
|
|
|
Q = I(:, q);
|
|
|
|
|
|
|
|
|
|
end
|