This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// lhs (left-hand-side), rhs (right-hand-side) | |
fun solve(lhs: Matrix, rhs: Matrix): Matrix? { | |
return inverse(lhs)?.let { it x rhs } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |