G

gaussupper

public
Guest Feb 03, 2025 Never 25
Clone
Plaintext gaussupper 50 lines (43 loc) | 1.69 KB
1
function augmented_to_upper_triangular_and_solve(A)
2
[rows, cols] = size(A);
3
4
// Step 1: Convert to upper triangular form using Gaussian elimination
5
for i = 1:min(rows, cols-1) // Only need to process up to the second last column
6
// Make sure the pivot element is non-zero
7
if A(i, i) == 0
8
for j = i+1:rows
9
if A(j, i) != 0
10
// Swap row i and row j
11
temp = A(i, :);
12
A(i, :) = A(j, :);
13
A(j, :) = temp;
14
break;
15
end
16
end
17
end
18
19
// Eliminate entries below the pivot
20
for j = i+1:rows
21
if A(j, i) != 0
22
// Row operation: subtract a multiple of row i from row j
23
factor = A(j, i) / A(i, i);
24
A(j, :) = A(j, :) - factor * A(i, :);
25
end
26
end
27
end
28
29
// Step 2: Perform back substitution to solve for variables
30
solution = zeros(rows, 1); // Initialize a vector to store the solution
31
32
// Start back substitution from the last row
33
for i = rows:-1:1
34
sum = A(i, cols); // The last column contains the constants (right-hand side of the equations)
35
36
// Subtract the known values (to the right of the diagonal)
37
for j = i+1:cols-1
38
sum = sum - A(i, j) * solution(j);
39
end
40
41
// Solve for the current variable
42
solution(i) = sum / A(i, i);
43
end
44
45
// Step 3: Output the upper triangular matrix and the solution
46
disp("Upper Triangular Matrix:");
47
disp(A);
48
disp("Solution (x, y, z):");
49
disp(solution);
50
endfunction