Basic matrix operations including multiplication and transpose
class Matrix(private val rows: Int, private val cols: Int) {
private val data: Array<DoubleArray> = Array(rows) { DoubleArray(cols) }
operator fun get(row: Int, col: Int): Double = data[row][col]
operator fun set(row: Int, col: Int, value: Double) {
data[row][col] = value
}
// Matrix multiplication
operator fun times(other: Matrix): Matrix {
require(this.cols == other.rows) {
"Cannot multiply matrices: columns of first matrix must equal rows of second matrix"
}
val result = Matrix(this.rows, other.cols)
for (i in 0 until this.rows) {
for (j in 0 until other.cols) {
var sum = 0.0
for (k in 0 until this.cols) {
sum += this[i, k] * other[k, j]
}
result[i, j] = sum
}
}
return result
}
// Matrix transpose
fun transpose(): Matrix {
val result = Matrix(cols, rows)
for (i in 0 until rows) {
for (j in 0 until cols) {
result[j, i] = this[i, j]
}
}
return result
}
// Matrix addition
operator fun plus(other: Matrix): Matrix {
require(this.rows == other.rows && this.cols == other.cols) {
"Matrices must have same dimensions for addition"
}
val result = Matrix(rows, cols)
for (i in 0 until rows) {
for (j in 0 until cols) {
result[i, j] = this[i, j] + other[i, j]
}
}
return result
}
override fun toString(): String {
return data.joinToString("\n") { row ->
row.joinToString(" ") { "%.2f".format(it) }
}
}
}
fun main() {
// Create matrices
val matrix1 = Matrix(2, 3).apply {
this[0, 0] = 1.0; this[0, 1] = 2.0; this[0, 2] = 3.0
this[1, 0] = 4.0; this[1, 1] = 5.0; this[1, 2] = 6.0
}
val matrix2 = Matrix(3, 2).apply {
this[0, 0] = 7.0; this[0, 1] = 8.0
this[1, 0] = 9.0; this[1, 1] = 10.0
this[2, 0] = 11.0; this[2, 1] = 12.0
}
println("Matrix 1:")
println(matrix1)
println("\nMatrix 2:")
println(matrix2)
println("\nMatrix 1 * Matrix 2:")
println(matrix1 * matrix2)
println("\nMatrix 1 Transposed:")
println(matrix1.transpose())
}
Views
Lines
Characters
Likes