Matrix Examples

Some basic examples. Mdoc calls toString() on each line, which actually, we don't want, but can't prevent for an opaque type. It is an annoyance which I believe to be justified - to be clear, you shouldn't use toString() to find out about matricies.

import vecxt.Matrix.*
import vecxt.BoundsCheck.DoBoundsCheck.yes
import narr.*

val nestedArr = NArray(
  NArray[Double](1.0, 2.0, 3.5),
  NArray[Double](3.0, 4.0, 5.0),
  NArray[Double](6.0, 7.0, 8.0)
)
// nestedArr: Array[Array[Double]] = [[D@270b527f

val matrix = Matrix.fromRows(nestedArr)
// matrix: Matrix = ([D@23ba044f,(3,3))
val matrix2 = Matrix.fromColumns(nestedArr)
// matrix2: Matrix = ([D@736b8ed4,(3,3))

matrix.shape
// res0: String = 3 x 3

matrix.print
// res1: String = 1.0 2.0 3.5
// 3.0 4.0 5.0
// 6.0 7.0 8.0

matrix2.print
// res2: String = 1.0 3.0 6.0
// 2.0 4.0 7.0
// 3.5 5.0 8.0

matrix.col(1).print
// res3: String = [2.0,4.0,7.0],

matrix.row(2).print
// res4: String = [6.0,7.0,8.0],

matrix.elementAt(1, 2)
// res5: Double = 7.0

There are only a small number of operations currently supported on matricies, but this sets out a paradigm. If it holds up, then adding more is a detail grind, rather than a risky time investment...

import vecxt.Matrix.*
import vecxt.BoundsCheck.DoBoundsCheck.yes
import narr.*
import vecxt.extensions.*

val mat1 = Matrix(NArray(1.0, 4.0, 2.0, 5.0, 3.0, 6.0), (2, 3))
// mat1: Matrix = ([D@7c556af2,(2,3))
val mat2 = Matrix(NArray(7.0, 9.0, 11.0, 8.0, 10, 12.0), (3, 2))
// mat2: Matrix = ([D@1b047ad,(3,2))
val result = mat1.matmul(mat2)
// result: Matrix = ([D@725bb3a8,(2,2))

result.print
// res6: String = 58.0 64.0
// 139.0 154.0

// @ is a reserved character, so we can't just copy numpy syntax... experimental
val result2 = mat1 @@ mat2
// result2: Matrix = ([D@5d699e19,(2,2))

result2.print
// res7: String = 58.0 64.0
// 139.0 154.0

val mat3 = mat2.transpose + mat1
// mat3: Matrix = ([D@a3c7dbc,(2,3))

Slicing

Index via a Int, NArray[Int] or a Range to slice a matrix. The :: operator is used to select all elements in a dimension.

import vecxt.Matrix.*
import vecxt.BoundsCheck.DoBoundsCheck.yes
import narr.*
import vecxt.extensions.*

val mat = Matrix.fromRows(
  NArray(
    NArray[Double](1.0, 2.0, 3.0),
    NArray[Double](4.0, 5.0, 6.0),
    NArray[Double](7.0, 8.0, 9.0)
  )
)
// mat: Matrix = ([D@9b2ce79,(3,3))
mat(::, ::).print
// res8: String = 1.0 2.0 3.0
// 4.0 5.0 6.0
// 7.0 8.0 9.0
mat(1, ::).print
// res9: String = 4.0 5.0 6.0
mat(::, 1).print
// res10: String = 2.0
// 5.0
// 8.0
mat(1, 1).print
// res11: String = 5.0
mat(0 to 1, 0 to 1).print
// res12: String = 1.0 2.0
// 4.0 5.0
mat(NArray.from[Int](Array(0, 2)), 0 to 1).print
// res13: String = 1.0 2.0
// 7.0 8.0
In this article