AAE-NA-Labs/01_Direct-Methods-for-Solving-Linear-Systems/Code/Alg6_RREF.m

47 lines
1.0 KiB
Mathematica
Raw Normal View History

2021-03-13 16:16:01 +01:00
function A = Alg6_RREF(A)
2021-03-13 20:23:23 +01:00
% Algorithm 6: Reduced Row Echelon Form (RREF)
% A = Alg6_RREF(A) returns RREF of matrix A.
2021-03-13 16:16:01 +01:00
2021-03-14 18:40:53 +01:00
[m, n] = size(A);
2021-03-13 16:16:01 +01:00
2021-03-14 18:40:53 +01:00
j = 0;
2021-03-13 16:16:01 +01:00
2021-03-14 18:40:53 +01:00
for k = 1 : m
j = j + 1;
if j > n
2021-03-13 16:16:01 +01:00
break
end
% We want the left-most coefficient to be 1 (pivot)
2021-03-14 18:40:53 +01:00
row = A(k, :);
if row(k) == 0
j = j + 1;
2021-03-13 16:16:01 +01:00
end
2021-03-14 18:40:53 +01:00
row = row/row(j);
A(k, :) = row;
2021-03-13 16:16:01 +01:00
2021-03-14 18:40:53 +01:00
for i = 1 : m
if i ~= k
A(i, :) = A(i, :)-(A(i, j))*row;
2021-03-13 16:16:01 +01:00
end
end
2021-03-14 18:40:53 +01:00
for i = k + 1 : m
A(i:end, k+1:end); % Partial matrix (in which we are looking for non-zero pivots)
A(i:end, k+1); % Left-most column
if ~any(A(i:end, k+1)) % If the left-most column has only zeros check the next one
k = k + 1;
2021-03-13 16:16:01 +01:00
end
2021-03-14 18:40:53 +01:00
A(i:end, k+1:end);
if A(i, k+1) == 0
non_zero_row = find(A(i:end,k+1), 1);
2021-03-13 16:16:01 +01:00
if isempty(non_zero_row)
continue
end
A([i, i+non_zero_row-1], :) = deal(A([i+non_zero_row-1, i], :));
end
end
end
end