Skip to content

Instantly share code, notes, and snippets.

@tikipatel
Created November 29, 2022 04:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tikipatel/be33e1d1eaf4c07a420797c49f8078d8 to your computer and use it in GitHub Desktop.
Save tikipatel/be33e1d1eaf4c07a420797c49f8078d8 to your computer and use it in GitHub Desktop.
Reduced Row Echelon Form in Swift
// Int and Double implementation of RREF
func rref(matrix: [[Int]]) -> [[Double]] {
var lead = 0
var returnMatrix = matrix.map({ (row) in
return row.map { Double($0) }
})
let rowCount = matrix.count
let columnCount = matrix[0].count
for r in 0..<rowCount {
if lead >= columnCount { break }
var x = r
while returnMatrix[x][lead] == 0 {
x += 1
if x == rowCount {
x = r
lead += 1
if columnCount == lead {
break
}
}
}
returnMatrix[x][r] = returnMatrix[r][x]
var lv = returnMatrix[r][lead]
returnMatrix[r] = returnMatrix[r].map { Double($0) / Double(lv) }
for i in 0..<rowCount {
if i != r {
lv = returnMatrix[i][lead]
returnMatrix[i] = zip(returnMatrix[r], returnMatrix[i]).map {$1 - $0*lv}
}
}
lead += 1
}
return returnMatrix
}
func rref(matrix: [[Double]]) -> [[Double]] {
var lead = 0
var returnMatrix = matrix
let rowCount = matrix.count
let columnCount = matrix[0].count
for r in 0..<rowCount {
if lead >= columnCount { break }
var x = r
while returnMatrix[x][lead] == 0 {
x += 1
if x == rowCount {
x = r
lead += 1
if columnCount == lead {
break
}
}
}
returnMatrix[x][r] = returnMatrix[r][x]
var lv = returnMatrix[r][lead]
returnMatrix[r] = returnMatrix[r].map { Double($0) / Double(lv) }
for i in 0..<rowCount {
if i != r {
lv = returnMatrix[i][lead]
returnMatrix[i] = zip(returnMatrix[r], returnMatrix[i]).map {$1 - $0*lv}
}
}
lead += 1
}
return returnMatrix
}
// Test: https://www.youtube.com/watch?v=OMHqfaLB1Uo
let mtx = [
[ 1, 1, 0, 5],
[ 0, 1, 2, -3],
[ 3, 0, 1, 10],]
print(rref(matrix: mtx))
// [[1.0, 0.0, 0.0, 4.0], [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, -2.0]]
// a = 4
// b = 1
// c = -2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment