AAE-NA-Labs/Direct Methods for Solving Linear Systems/Alg3.m

30 lines
556 B
Mathematica
Raw Normal View History

2021-03-21 19:45:18 +01:00
function b = Al3(L, b)
2021-03-14 18:40:53 +01:00
% Algorithm 3: Forward Substitution
% b = Alg3_forward_substitution(L, b) overwrites b with the solution to
% Lx = b.
2021-03-06 18:17:36 +01:00
2021-03-14 18:40:53 +01:00
[m, n] = size(L);
2021-03-06 18:17:36 +01:00
2021-03-14 18:40:53 +01:00
if m ~= n
error('Matrix is not square!')
end
if length(b) ~= m
error('Vector b has wrong length!')
end
if det(L) < eps
error("Matrix is not nonsingular!")
end
% The following algorithm is based on the Algrotihm 3.1.1 from [2].
% b(m, :) so that matrices are also accepted
b(1, :) = b(1, :)/L(1,1);
for i = 2:m
b(i, :) = (b(i, :) - L(i, 1:i-1)*b(1:i-1, :))/L(i, i);
end
2021-03-06 18:17:36 +01:00
end