Skip to content

Instantly share code, notes, and snippets.

View dionsaputra's full-sized avatar
🏠
Working from home

Dion Saputra dionsaputra

🏠
Working from home
View GitHub Profile
// lhs (left-hand-side), rhs (right-hand-side)
fun solve(lhs: Matrix, rhs: Matrix): Matrix? {
return inverse(lhs)?.let { it x rhs }
}
// matrix cross-product
infix fun x(other: Matrix): Matrix {
require(cols == other.rows)
val res = Matrix(rows, other.cols, Array(rows * other.cols) { 0.0 })
for (i in 0 until rows) {
for (j in 0 until other.cols) {
for (k in 0 until cols) res[i,j] += (this[i,k] * other[k,j])
}
}
return res
fun inverse(matrix: Matrix): Matrix? {
require(matrix.rows == matrix.cols)
// check matrix invertible
if (determinant(matrix).equalsDelta(0.0)) return null
// copy matrix
val inverse = Matrix.diagonal(matrix.rows, 1.0, 0.0)
val temp = Matrix(
matrix.rows,
fun determinant(matrix: Matrix): Double {
require(matrix.rows == matrix.cols)
if (matrix.rows == 1) return matrix[0,0]
if (matrix.rows == 2) return (
matrix[0,0] * matrix[1,1] -
matrix[0,1] * matrix[1,0]
)
var det = 0.0
data class Matrix(val rows: Int, val cols: Int) {
lateinit var elements: DoubleArray
private fun index(r: Int, c: Int) = r * cols + c
operator fun get(r: Int, c: Int) = elements[index(r,c)]
operator fun set(r: Int, c: Int, element: Double) {
elements[index(r,c)] = element