Vectors and matrices
This page covers the operations most programs use every day: making vectors and matrices, reading their entries, taking rows and columns, doing arithmetic, and solving a square system. Everything here comes from one import:
import gale.linalg.*Make vectors and matrices
Section titled “Make vectors and matrices”Vec makes a dense vector of Doubles. Matrix(rows, cols) takes its values
in row-major order, so you write the matrix as you would on paper:
val x = Vec(1.0, 2.0, 3.0)
val a = Matrix(3, 3)( 2.0, 1.0, 0.0, 1.0, 3.0, 1.0, 0.0, 1.0, 4.0)
(x.length, a.rows, a.cols)// res0: Tuple3[Int, Int, Int] = (3, 3, 3)When each entry follows from its position, use tabulate. zeros, fill,
and Matrix.eye cover the other common cases:
val hilbert = Matrix.tabulate(3, 3)((i, j) => 1.0 / (i + j + 1))val ones = Vec.fill(3)(1.0)val identity = Matrix.eye(3)
hilbert.valuesRowMajor// res1: Seq[Double] = Vector(// 1.0,// 0.5,// 0.3333333333333333,// 0.5,// 0.3333333333333333,// 0.25,// 0.3333333333333333,// 0.25,// 0.2// )The values are DVec and DMat. Neither has a readable toString, so the
examples on these pages print them with toSeq and valuesRowMajor.
Read entries, rows, and columns
Section titled “Read entries, rows, and columns”Indices start at zero. a(i, j) reads one entry and x(i) one element.
row, col, and slice select part of a matrix; slice bounds include the
first index and exclude the last.
a(1, 2)// res2: Double = 1.0x(0)// res3: Double = 1.0a.row(1).toSeq// res4: Seq[Double] = Vector(1.0, 3.0, 1.0)a.col(2).toSeq// res5: Seq[Double] = Vector(0.0, 1.0, 4.0)a.slice(0, 2, 1, 3).valuesRowMajor// res6: Seq[Double] = Vector(1.0, 0.0, 3.0, 1.0)row, col, slice, and the transpose a.t are views: they share the
original’s storage instead of copying it. Sharing is safe because Gale’s
vectors and matrices never change once made. To change an entry, ask for a new
value:
val b = a.updated(0, 0, 10.0)(a(0, 0), b(0, 0))// res7: Tuple2[Double, Double] = (2.0, 10.0)updated copies the whole matrix, which is fine for a few changes. To fill
many entries, use tabulate, or a builder as described in
Ownership.
Do arithmetic
Section titled “Do arithmetic”+ and - work entry by entry. * with a number scales; * with a vector
or matrix is the matrix product. dot and norm2 give the inner product and
Euclidean length of vectors.
(a * x).toSeq// res8: Seq[Double] = Vector(4.0, 10.0, 14.0)(a.t * a).valuesRowMajor// res9: Seq[Double] = Vector(5.0, 5.0, 1.0, 5.0, 11.0, 7.0, 1.0, 7.0, 17.0)(a + identity).valuesRowMajor// res10: Seq[Double] = Vector(3.0, 1.0, 0.0, 1.0, 4.0, 1.0, 0.0, 1.0, 5.0)(x * 2.0 - ones).toSeq// res11: Seq[Double] = Vector(1.0, 3.0, 5.0)(x.dot(ones), x.norm2)// res12: Tuple2[Double, Double] = (6.0, 3.7416573867739413)Each operation checks shapes first. Multiplying a 3 × 3 matrix by a vector of
length 2 throws a LinAlgError that names the mismatch, at the line that made
the mistake:
val mismatch = try a * Vec(1.0, 2.0) "no error" catch case e: LinAlgError => e.getClass.getSimpleName// mismatch: String = "VectorLengthMismatch"Work entry by entry
Section titled “Work entry by entry”* between two matrices is the matrix product. For the entry-by-entry
product, or to apply a function to every entry, import gale.syntax.all.*
and use pointwise:
import gale.syntax.all.*
(a.pointwise * a).valuesRowMajor// res13: Seq[Double] = Vector(4.0, 1.0, 0.0, 1.0, 9.0, 1.0, 0.0, 1.0, 16.0)a.pointwise.map(v => v * v + 1.0).valuesRowMajor// res14: Seq[Double] = Vector(5.0, 2.0, 1.0, 2.0, 10.0, 2.0, 1.0, 2.0, 17.0)Numerics.exp(x).toSeq// res15: Seq[Double] = Vector(// 2.718281828459045,// 7.38905609893065,// 20.085536923187668// )Numerics also has log, log1p, sigmoid, and a stable logSumExp.
Sum, average, and find extremes
Section titled “Sum, average, and find extremes”A reduction without an axis covers every entry. Axis.Rows gives one value
per row and Axis.Cols one value per column.
val scores = Matrix(2, 3)( 1.0, 4.0, 2.0, 3.0, 0.0, 5.0)
(scores.sum, scores.max, scores.argmax)// res16: Tuple3[Double, Double, Tuple2[Int, Int]] = (15.0, 5.0, (1, 2))scores.sum(Axis.Rows).toSeq// res17: Seq[Double] = Vector(7.0, 8.0)scores.mean(Axis.Cols).toSeq// res18: Seq[Double] = Vector(2.0, 2.0, 3.5)(x.sum, x.mean, x.argmax)// res19: Tuple3[Double, Double, Int] = (6.0, 2.0, 2)argmax on a matrix returns a (row, column) pair. To subtract each column’s
mean from that column, build the matrix of means and subtract it:
val means = scores.mean(Axis.Cols)val centered = scores - Matrix.tabulate(scores.rows, scores.cols)((_, j) => means(j))centered.valuesRowMajor// res20: Seq[Double] = Vector(-1.0, 2.0, -1.5, 1.0, -2.0, 1.5)Reductions and norms covers norms, ties and NaN, exact sums, and softmax.
Solve a square system
Section titled “Solve a square system”a.solve(rhs) solves A x = b. It returns an Either, because a singular
matrix has no unique solution and the caller should decide what that means:
val rhs = a * xa.solve(rhs).map(_.toSeq)// res21: Either[LinAlgError, Seq[Double]] = Right(Vector(1.0, 2.0, 3.0))val singular = Matrix(2, 2)( 1.0, 2.0, 2.0, 4.0)singular.solve(Vec(1.0, 1.0))// res22: Either[LinAlgError, DVec] = Left(SingularMatrix(1))The second matrix has a zero determinant, so the result is a Left naming
the problem rather than a vector of meaningless numbers. Use
.orThrow when a failure should stop the program, as in a test or a script.
Next steps
Section titled “Next steps”- Dense systems and least squares covers many right-hand sides, rectangular systems, and keeping a factorization to reuse.
- Reductions and norms covers sums, means, extrema, norms, and stable softmax.
- Sparse matrices and operators covers matrices that are mostly zeros.
- Core concepts explains views, failures, and backends in more depth.