@@ -3,41 +3,44 @@ function gaussian_elimination(A::Array{Float64,2})
3
3
rows = size (A,1 )
4
4
cols = size (A,2 )
5
5
6
+ # Row index
7
+ row = 1
8
+
6
9
# Main loop going through all columns
7
- for k = 1 : min (rows, cols)
10
+ for col = 1 : ( cols- 1 )
8
11
9
12
# Step 1: finding the maximum element for each column
10
- max_index = indmax (abs .(A[k : end ,k ])) + k - 1
13
+ max_index = indmax (abs .(A[row : end ,col ])) + row - 1
11
14
12
15
# Check to make sure matrix is good!
13
- if (A[max_index, k ] == 0 )
14
- println (" matrix is singular! End! " )
15
- exit ( 0 )
16
+ if (A[max_index, col ] == 0 )
17
+ println (" matrix is singular!" )
18
+ continue
16
19
end
17
20
18
21
# Step 2: swap row with highest value for that column to the top
19
22
temp_vector = A[max_index, :]
20
- A[max_index, :] = A[k, :]
21
- A[k, :] = temp_vector
22
- # println(A)
23
+ A[max_index, :] = A[row, :]
24
+ A[row, :] = temp_vector
23
25
24
26
# Loop for all remaining rows
25
- for i = (k + 1 ): rows
27
+ for i = (row + 1 ): rows
26
28
27
29
# Step 3: finding fraction
28
- fraction = A[i,k ]/ A[k,k ]
30
+ fraction = A[i,col ]/ A[row,col ]
29
31
30
32
# loop through all columns for that row
31
- for j = (k + 1 ): cols
33
+ for j = (col + 1 ): cols
32
34
33
35
# Step 4: re-evaluate each element
34
- A[i,j] -= A[k ,j]* fraction
36
+ A[i,j] -= A[row ,j]* fraction
35
37
36
38
end
37
39
38
40
# Step 5: Set lower elements to 0
39
- A[i,k ] = 0
41
+ A[i,col ] = 0
40
42
end
43
+ row += 1
41
44
end
42
45
end
43
46
@@ -63,18 +66,51 @@ function back_substitution(A::Array{Float64,2})
63
66
return soln
64
67
end
65
68
69
+
70
+ function gauss_jordan (A:: Array{Float64,2} )
71
+
72
+ rows = size (A,1 )
73
+ cols = size (A,2 )
74
+
75
+
76
+ # After this, we know what row to start on (r-1)
77
+ # to go back through the matrix
78
+ row = 1
79
+ for col = 1 : cols- 1
80
+ if (A[row, col] != 0 )
81
+
82
+ # divide row by pivot and leaving pivot as 1
83
+ for i = cols: - 1 : col
84
+ A[row,i] /= A[row,col]
85
+ end
86
+
87
+ # subtract value from above row and set values above pivot to 0
88
+ for i = 1 : row- 1
89
+ for j = cols: - 1 : col
90
+ A[i,j] -= A[i,col]* A[row,j]
91
+ end
92
+ end
93
+ row += 1
94
+ end
95
+ end
96
+
97
+ return A
98
+ end
99
+
66
100
function main ()
67
101
A = [2. 3 4 6 ;
68
102
1 2 3 4 ;
69
103
3 - 4 0 10 ]
70
104
71
105
gaussian_elimination (A)
72
106
println (A)
107
+
108
+ reduced = gauss_jordan (A)
109
+ println (reduced)
110
+
73
111
soln = back_substitution (A)
112
+ println (soln)
74
113
75
- for element in soln
76
- println (element)
77
- end
78
114
end
79
115
80
116
main ()
0 commit comments