class Matrix<T : Number> private constructor(private val rows: Int, private val cols: Int, private val data: Array<Array<T>>) {
constructor(rows: Int, cols: Int) : this(rows, cols, Array(rows) { Array(cols) { 0 as T } })
operator fun get(row: Int, col: Int): T = data[row][col]
operator fun set(row: Int, col: Int, value: T) {
data[row][col] = value
}
operator fun plus(other: Matrix<T>): Matrix<T> {
require(rows == other.rows && cols == other.cols) { "Matrices must have the same dimensions for addition" }
val result = Matrix<T>(rows, cols)
for (i in 0 until rows) {
for (j in 0 until cols) {
result[i, j] = when (data[i][j]) {
is Int -> (data[i][j] as Int) + (other[i, j] as Int) as T
is Double -> (data[i][j] as Double) + (other[i, j] as Double) as T
else -> throw UnsupportedOperationException("Unsupported type for addition")
}
}
}
return result
}
operator fun times(other: Matrix<T>): Matrix<T> {
require(cols == other.rows) { "Number of columns in the first matrix must be equal to the number of rows in the second matrix for multiplication" }
val result = Matrix<T>(rows, other.cols)
for (i in 0 until rows) {
for (j in 0 until other.cols) {
var sum = 0.0
for (k in 0 until cols) {
sum += when (data[i][k]) {
is Int -> (data[i][k] as Int) * (other[k, j] as Int)
is Double -> (data[i][k] as Double) * (other[k, j] as Double)
else -> throw UnsupportedOperationException("Unsupported type for multiplication")
}
}
result[i, j] = sum as T
}
}
return result
}
}