Matrix Examples
Some examples. You shouldn't use toString()
to find out about matricies. Mdoc calls it on each line anyway - not much i can do about that.
import vecxt.all.*
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@30749de8
val matrix = Matrix.fromRows(nestedArr)
// matrix: Matrix = ([D@4a5c25f6,(3,3))
val matrix2 = Matrix.fromColumns(nestedArr)
// matrix2: Matrix = ([D@6138bbe5,(3,3))
matrix.shape
// res0: String = 3 x 3
matrix.printMat
// res1: String = 1.0 2.0 3.5
// 3.0 4.0 5.0
// 6.0 7.0 8.0
matrix2.printMat
// res2: String = 1.0 3.0 6.0
// 2.0 4.0 7.0
// 3.5 5.0 8.0
matrix.col(1).printArr
// res3: String = [2.0,4.0,7.0]
matrix.row(2).printArr
// res4: String = [6.0,7.0,8.0]
// Note that indexing is done via a tuple.
matrix((1, 2))
// res5: Double = 5.0
More matrix operations...
import vecxt.all.*
import vecxt.BoundsCheck.DoBoundsCheck.yes
import narr.*
val mat1 = Matrix(NArray(1.0, 4.0, 2.0, 5.0, 3.0, 6.0), (2, 3))
// mat1: Matrix = ([D@1d42d4bf,(2,3))
val mat2 = Matrix(NArray(7.0, 9.0, 11.0, 8.0, 10, 12.0), (3, 2))
// mat2: Matrix = ([D@108ed05b,(3,2))
val result = mat1.matmul(mat2)
// result: Matrix = ([D@3db22d30,(2,2))
result.printMat
// 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@2a88200e,(2,2))
result2.printMat
// res7: String = 58.0 64.0
// 139.0 154.0
// opperator precedence...
val result3 = Matrix.eye(2) + mat1 @@ mat2
// result3: Matrix = ([D@175437e0,(2,2))
result3.printMat
// res8: String = 59.0 64.0
// 139.0 155.0
val mat3 = mat2.transpose + mat1
// mat3: Matrix = ([D@f00be49,(2,3))
mat3.printMat
// res9: String = 8.0 11.0 14.0
// 12.0 15.0 18.0
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.all.*
import vecxt.BoundsCheck.DoBoundsCheck.yes
import narr.*
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@65b0ada5,(3,3))
mat(::, ::).printMat
// res10: String = 1.0 2.0 3.0
// 4.0 5.0 6.0
// 7.0 8.0 9.0
mat(1, ::).printMat
// res11: String = 4.0 5.0 6.0
mat(::, 1).printMat
// res12: String = 2.0
// 5.0
// 8.0
mat(1, 1).printMat
// res13: String = 5.0
mat(0 to 1, 0 to 1).printMat
// res14: String = 1.0 2.0
// 4.0 5.0
mat(NArray.from[Int](Array(0, 2)), 0 to 1).printMat
// res15: String = 1.0 2.0
// 7.0 8.0
In this article