Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updating gaussian elimination to be more general #219

Merged
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,43 +1,47 @@
using DataStructures
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not needed anymore.

function gaussian_elimination(A::Array{Float64,2})

rows = size(A,1)
cols = size(A,2)

# Row index
row = 1

# Main loop going through all columns
for k = 1:min(rows,cols)
for col = 1:(cols-1)

# Step 1: finding the maximum element for each column
max_index = indmax(abs.(A[k:end,k])) + k-1
max_index = indmax(abs.(A[row:end,col])) + row-1

# Check to make sure matrix is good!
if (A[max_index, k] == 0)
println("matrix is singular! End!")
exit(0)
if (A[max_index, col] == 0)
println("matrix is singular!")
continue
end

# Step 2: swap row with highest value for that column to the top
temp_vector = A[max_index, :]
A[max_index, :] = A[k, :]
A[k, :] = temp_vector
#println(A)
A[max_index, :] = A[row, :]
A[row, :] = temp_vector

# Loop for all remaining rows
for i = (k+1):rows
for i = (row+1):rows

# Step 3: finding fraction
fraction = A[i,k]/A[k,k]
fraction = A[i,col]/A[row,col]

# loop through all columns for that row
for j = (k+1):cols
for j = (col+1):cols

# Step 4: re-evaluate each element
A[i,j] -= A[k,j]*fraction
A[i,j] -= A[row,j]*fraction

end

# Step 5: Set lower elements to 0
A[i,k] = 0
A[i,col] = 0
end
row += 1
end
end

Expand All @@ -63,18 +67,51 @@ function back_substitution(A::Array{Float64,2})
return soln
end


function gauss_jordan(A::Array{Float64,2})

rows = size(A,1)
cols = size(A,2)


# After this, we know what row to start on (r-1)
# to go back through the matrix
row = 1
for col = 1:cols-1
if (A[row, col] != 0)

# divide row by pivot and leaving pivot as 1
for i = cols:-1:col
A[row,i] /= A[row,col]
end

# subtract value from above row and set values above pivot to 0
for i = 1:row-1
for j = cols:-1:col
A[i,j] -= A[i,col]*A[row,j]
end
end
row += 1
end
end

return A
end

function main()
A = [2. 3 4 6;
1 2 3 4;
3 -4 0 10]

gaussian_elimination(A)
println(A)

reduced = gauss_jordan(A)
println(reduced)

soln = back_substitution(A)
println(soln)

for element in soln
println(element)
end
end

main()
Loading