-
Notifications
You must be signed in to change notification settings - Fork 0
/
gaussJordanElimination.m
65 lines (60 loc) · 2.07 KB
/
gaussJordanElimination.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
function [X, isSingular] = gaussJordanElimination(coefficients, results, n, tolerance)
% coefficients is the coeffecients square matrix
% results is the results matrix
% n is the number of equations
% tolerance is the smallest allowable scaled pivot
% X is the solution matrix
% isSingular is a boolean indicating if the system is singular, ie not solvable
[coefficients, results, isSingular] = elimination(coefficients, results, n, tolerance);
if ~isSingular
[X] = substitution(coefficients, results, n);
end
end
function [coefficients, results, isSingular] = elimination(coefficients, results, n, tolerance)
for row = 1 : n
[coefficients, results] = pivot(coefficients, results, n, row);
if abs(coefficients(row, row)) < tolerance
isSingular = true;
return;
end
% forward elimination
range = 1 : n;
for i = range(range ~= row)
factor = coefficients(i, row) / coefficients(row, row);
for j = row + 1 : n
coefficients(i, j) = coefficients(i, j) - factor * coefficients(row, j);
end
results(i) = results(i) - factor * results(row);
end
end
isSingular = false;
end
function [coefficients, results] = pivot(coefficients, results, n, row)
pivotRow = row;
% Find the largest coefficient in column k
max = abs(coefficients(row, row));
for i = row + 1 : n
temp = abs(coefficients(i, row));
if temp > max
max = temp;
pivotRow = i;
end
end
% swapping the rows
if pivotRow ~= row
for j = row : n
temp = coefficients(pivotRow, j);
coefficients(pivotRow, j) = coefficients(row, j);
coefficients(row, j) = temp;
end
temp = results(pivotRow);
results(pivotRow) = results(row);
results(row) = temp;
end
end
function [X] = substitution(coefficients, results, n)
X = zeros(1, n);
for i = 1 : n
X(i) = results(i) / coefficients(i, i);
end
end