`import "github.com/gonum/matrix/mat64"`

Package mat64 provides implementations of float64 matrix structures and linear algebra operations on them.

This section provides a quick overview of the mat64 package. The following sections provide more in depth commentary.

mat64 provides:

- Interfaces for Matrix classes (Matrix, Symmetric, Triangular) - Concrete implementations (Dense, SymDense, TriDense) - Methods and functions for using matrix data (Add, Trace, SymRankOne) - Types for constructing and using matrix factorizations (QR, LU)

A matrix may be constructed through the corresponding New function. If no backing array is provided the matrix will be initialized to all zeros.

// Allocate a zeroed matrix of size 3×5 zero := mat64.NewDense(3, 5, nil)

If a backing data slice is provided, the matrix will have those elements. Matrices are all stored in row-major format.

// Generate a 6×6 matrix of random values. data := make([]float64, 36) for i := range data { data[i] = rand.NormFloat64() } a := mat64.NewDense(6, 6, data)

Operations involving matrix data are implemented as functions when the values of the matrix remain unchanged

tr := mat64.Trace(a)

and are implemented as methods when the operation modifies the receiver.

zero.Copy(a)

Receivers must be the correct size for the matrix operations, otherwise the operation will panic. As a special case for convenience, a zero-sized matrix will be modified to have the correct size, allocating data if necessary.

var c mat64.Dense // construct a new zero-sized matrix c.Mul(a, a) // c is automatically adjusted to be 6×6

The Matrix interface is the common link between the concrete types. The Matrix interface is defined by three functions: Dims, which returns the dimensions of the Matrix, At, which returns the element in the specified location, and T for returning a Transpose (discussed later). All of the concrete types can perform these behaviors and so implement the interface. Methods and functions are designed to use this interface, so in particular the method

func (m *Dense) Mul(a, b Matrix)

constructs a *Dense from the result of a multiplication with any Matrix types, not just *Dense. Where more restrictive requirements must be met, there are also the Symmetric and Triangular interfaces. For example, in

func (s *SymDense) AddSym(a, b Symmetric)

the Symmetric interface guarantees a symmetric result.

The T method is used for transposition. For example, c.Mul(a.T(), b) computes c = a^T * b. The mat64 types implement this method using an implicit transpose — see the Transpose type for more details. Note that some operations have a transpose as part of their definition, as in *SymDense.SymOuterK.

Matrix factorizations, such as the LU decomposition, typically have their own specific data storage, and so are each implemented as a specific type. The factorization can be computed through a call to Factorize

var lu mat64.LU lu.Factorize(a)

The elements of the factorization can be extracted through methods on the appropriate type, i.e. *TriDense.LFromLU and *TriDense.UFromLU. Alternatively, they can be used directly, as in *Dense.SolveLU. Some factorizations can be updated directly, without needing to update the original matrix and refactorize, as in *LU.RankOne.

BLAS and LAPACK are the standard APIs for linear algebra routines. Many operations in mat64 are implemented using calls to the wrapper functions in gonum/blas/blas64 and gonum/lapack/lapack64. By default, blas64 and lapack64 call the native Go implementations of the routines. Alternatively, it is possible to use C-based implementations of the APIs through the respective cgo packages and "Use" functions. The Go implementation of LAPACK makes calls through blas64, so if a cgo BLAS implementation is registered, the lapack64 calls will be partially executed in Go and partially executed in C.

The Matrix abstraction enables efficiency as well as interoperability. Go's type reflection capabilities are used to choose the most efficient routine given the specific concrete types. For example, in

c.Mul(a, b)

if a and b both implement RawMatrixer, that is, they can be represented as a blas64.General, blas64.Gemm (general matrix multiplication) is called, while instead if b is a RawSymmetricer blas64.Symm is used (general-symmetric multiplication), and if b is a *Vector blas64.Gemv is used.

There are many possible type combinations and special cases. No specific guarantees are made about the performance of any method, and in particular, note that an abstract matrix type may be copied into a concrete type of the corresponding value. If there are specific special cases that are needed, please submit a pull-request or file an issue.

Matrix input arguments to functions are never directly modified. If an operation changes Matrix data, the mutated matrix will be the receiver of a function.

For convenience, a matrix may be used as both a receiver and as an input, e.g.

a.Pow(a, 6) v.SolveVec(a.T(), v)

though in many cases this will cause an allocation (see Element Aliasing). An exception to this rule is Copy, which does not allow a.Copy(a.T()).

Most methods in mat64 modify receiver data. It is forbidden for the modified data region of the receiver to overlap the used data area of the input arguments. The exception to this rule is when the method receiver is equal to one of the input arguments, as in the a.Pow(a, 6) call above, or its implicit transpose.

This prohibition is to help avoid subtle mistakes when the method needs to read from and write to the same data region. There are ways to make mistakes using the mat64 API, and mat64 functions will detect and complain about those. There are many ways to make mistakes by excursion from the mat64 API via interaction with raw matrix values.

If you need to read the rest of this section to understand the behavior of your program, you are being clever. Don't be clever. If you must be clever, blas64 and lapack64 may be used to call the behavior directly.

mat64 will use the following rules to detect overlap between the receiver and one of the inputs:

- the input implements one of the Raw methods, and - the Raw type matches that of the receiver or one is a RawMatrixer and the other is a RawVectorer, and - the address ranges of the backing data slices overlap, and - the strides differ or there is an overlap in the used data elements.

If such an overlap is detected, the method will panic.

The following cases will not panic:

- the data slices do not overlap, - there is pointer identity between the receiver and input values after the value has been untransposed if necessary.

mat64 will not attempt to detect element overlap if the input does not implement a Raw method, or if the Raw method differs from that of the receiver except when a conversion has occurred through a mat64 API function. Method behavior is undefined if there is undetected overlap.

- func Col(dst []float64, j int, a Matrix) []float64
- func Cond(a Matrix, norm float64) float64
- func Det(a Matrix) float64
- func Dot(a, b *Vector) float64
- func Equal(a, b Matrix) bool
- func EqualApprox(a, b Matrix, epsilon float64) bool
- func Formatted(m Matrix, options ...FormatOption) fmt.Formatter
- func Inner(x *Vector, A Matrix, y *Vector) float64
- func LogDet(a Matrix) (det float64, sign float64)
- func Max(a Matrix) float64
- func Min(a Matrix) float64
- func Norm(a Matrix, norm float64) float64
- func Row(dst []float64, i int, a Matrix) []float64
- func Sum(a Matrix) float64
- func Trace(a Matrix) float64
- type BandWidther
- type Cholesky
- func (c *Cholesky) Clone(chol *Cholesky)
- func (c *Cholesky) Det() float64
- func (c *Cholesky) Factorize(a Symmetric) (ok bool)
- func (c *Cholesky) LogDet() float64
- func (c *Cholesky) Reset()
- func (c *Cholesky) SetFromU(t *TriDense)
- func (c *Cholesky) Size() int
- func (c *Cholesky) SymRankOne(orig *Cholesky, alpha float64, x *Vector) (ok bool)
- type Cloner
- type ColViewer
- type Copier
- type Dense
- func DenseCopyOf(a Matrix) *Dense
- func NewDense(r, c int, data []float64) *Dense
- func (m *Dense) Add(a, b Matrix)
- func (m *Dense) Apply(fn func(i, j int, v float64) float64, a Matrix)
- func (m *Dense) At(i, j int) float64
- func (m *Dense) Augment(a, b Matrix)
- func (m *Dense) Caps() (r, c int)
- func (m *Dense) Clone(a Matrix)
- func (m *Dense) ColView(j int) *Vector
- func (m *Dense) Copy(a Matrix) (r, c int)
- func (m *Dense) Dims() (r, c int)
- func (m *Dense) DivElem(a, b Matrix)
- func (m *Dense) EigenvectorsSym(e *EigenSym)
- func (m *Dense) Exp(a Matrix)
- func (m *Dense) Grow(r, c int) Matrix
- func (m *Dense) Inverse(a Matrix) error
- func (m *Dense) LFromLQ(lq *LQ)
- func (m Dense) MarshalBinary() ([]byte, error)
- func (m Dense) MarshalBinaryTo(w io.Writer) (int, error)
- func (m *Dense) Mul(a, b Matrix)
- func (m *Dense) MulElem(a, b Matrix)
- func (m *Dense) Outer(alpha float64, x, y *Vector)
- func (m *Dense) Permutation(r int, swaps []int)
- func (m *Dense) Pow(a Matrix, n int)
- func (m *Dense) Product(factors ...Matrix)
- func (m *Dense) QFromGSVD(gsvd *GSVD)
- func (m *Dense) QFromLQ(lq *LQ)
- func (m *Dense) QFromQR(qr *QR)
- func (m *Dense) RFromQR(qr *QR)
- func (m *Dense) RankOne(a Matrix, alpha float64, x, y *Vector)
- func (m *Dense) RawMatrix() blas64.General
- func (m *Dense) RawRowView(i int) []float64
- func (m *Dense) Reset()
- func (m *Dense) RowView(i int) *Vector
- func (m *Dense) Scale(f float64, a Matrix)
- func (m *Dense) Set(i, j int, v float64)
- func (m *Dense) SetCol(j int, src []float64)
- func (m *Dense) SetRawMatrix(b blas64.General)
- func (m *Dense) SetRow(i int, src []float64)
- func (m *Dense) SigmaAFromGSVD(gsvd *GSVD)
- func (m *Dense) SigmaBFromGSVD(gsvd *GSVD)
- func (m *Dense) Slice(i, k, j, l int) Matrix
- func (m *Dense) Solve(a, b Matrix) error
- func (m *Dense) SolveCholesky(chol *Cholesky, b Matrix) error
- func (m *Dense) SolveLQ(lq *LQ, trans bool, b Matrix) error
- func (m *Dense) SolveLU(lu *LU, trans bool, b Matrix) error
- func (m *Dense) SolveQR(qr *QR, trans bool, b Matrix) error
- func (m *Dense) Stack(a, b Matrix)
- func (m *Dense) Sub(a, b Matrix)
- func (m *Dense) T() Matrix
- func (m *Dense) UFromGSVD(gsvd *GSVD)
- func (m *Dense) UFromHOGSVD(gsvd *HOGSVD, n int)
- func (m *Dense) UFromSVD(svd *SVD)
- func (m *Dense) UnmarshalBinary(data []byte) error
- func (m *Dense) UnmarshalBinaryFrom(r io.Reader) (int, error)
- func (m *Dense) VFromGSVD(gsvd *GSVD)
- func (m *Dense) VFromHOGSVD(gsvd *HOGSVD)
- func (m *Dense) VFromSVD(svd *SVD)
- func (m *Dense) View(i, j, r, c int) Matrix
- func (m *Dense) ZeroRFromGSVD(gsvd *GSVD)
- type Eigen
- func (e *Eigen) Factorize(a Matrix, left, right bool) (ok bool)
- func (e *Eigen) LeftVectors() *Dense
- func (e *Eigen) Values(dst []complex128) []complex128
- func (e *Eigen) Vectors() *Dense
- type EigenSym
- func (e *EigenSym) Factorize(a Symmetric, vectors bool) (ok bool)
- func (e *EigenSym) Values(dst []float64) []float64
- type FormatOption
- func DotByte(b byte) FormatOption
- func Excerpt(m int) FormatOption
- func Prefix(p string) FormatOption
- func Squeeze() FormatOption
- type GSVD
- func (gsvd *GSVD) Factorize(a, b Matrix, kind matrix.GSVDKind) (ok bool)
- func (gsvd *GSVD) GeneralizedValues(v []float64) []float64
- func (gsvd *GSVD) Kind() matrix.GSVDKind
- func (gsvd *GSVD) Rank() (k, l int)
- func (gsvd *GSVD) ValuesA(s []float64) []float64
- func (gsvd *GSVD) ValuesB(s []float64) []float64
- type Grower
- type HOGSVD
- func (gsvd *HOGSVD) Err() error
- func (gsvd *HOGSVD) Factorize(m ...Matrix) (ok bool)
- func (gsvd *HOGSVD) Len() int
- func (gsvd *HOGSVD) Values(s []float64, n int) []float64
- type LQ
- type LU
- func (lu *LU) Det() float64
- func (lu *LU) Factorize(a Matrix)
- func (lu *LU) LogDet() (det float64, sign float64)
- func (lu *LU) Pivot(swaps []int) []int
- func (lu *LU) RankOne(orig *LU, alpha float64, x, y *Vector)
- func (lu *LU) Reset()
- type Matrix
- type Mutable
- type MutableSymmetric
- type QR
- type RawColViewer
- type RawMatrixSetter
- type RawMatrixer
- type RawRowViewer
- type RawSymmetricer
- type RawTriangular
- type RawVectorer
- type Reseter
- type RowViewer
- type SVD
- func (svd *SVD) Cond() float64
- func (svd *SVD) Factorize(a Matrix, kind matrix.SVDKind) (ok bool)
- func (svd *SVD) Kind() matrix.SVDKind
- func (svd *SVD) Values(s []float64) []float64
- type SymDense
- func NewSymDense(n int, data []float64) *SymDense
- func (s *SymDense) AddSym(a, b Symmetric)
- func (s *SymDense) At(i, j int) float64
- func (s *SymDense) CopySym(a Symmetric) int
- func (s *SymDense) Dims() (r, c int)
- func (s *SymDense) FromCholesky(chol *Cholesky)
- func (s *SymDense) GrowSquare(n int) Matrix
- func (s *SymDense) InverseCholesky(chol *Cholesky) error
- func (s *SymDense) PowPSD(a Symmetric, pow float64) error
- func (s *SymDense) RankTwo(a Symmetric, alpha float64, x, y *Vector)
- func (s *SymDense) RawSymmetric() blas64.Symmetric
- func (s *SymDense) Reset()
- func (s *SymDense) ScaleSym(f float64, a Symmetric)
- func (s *SymDense) SetRawSymmetric(b blas64.Symmetric)
- func (s *SymDense) SetSym(i, j int, v float64)
- func (s *SymDense) SliceSquare(i, k int) Matrix
- func (s *SymDense) SubsetSym(a Symmetric, set []int)
- func (s *SymDense) SymOuterK(alpha float64, x Matrix)
- func (s *SymDense) SymRankK(a Symmetric, alpha float64, x Matrix)
- func (s *SymDense) SymRankOne(a Symmetric, alpha float64, x *Vector)
- func (s *SymDense) Symmetric() int
- func (s *SymDense) T() Matrix
- func (s *SymDense) ViewSquare(i, n int) Matrix
- type Symmetric
- type Transpose
- func (t Transpose) At(i, j int) float64
- func (t Transpose) Dims() (r, c int)
- func (t Transpose) T() Matrix
- func (t Transpose) Untranspose() Matrix
- type TransposeTri
- func (t TransposeTri) At(i, j int) float64
- func (t TransposeTri) Dims() (r, c int)
- func (t TransposeTri) T() Matrix
- func (t TransposeTri) TTri() Triangular
- func (t TransposeTri) Triangle() (int, matrix.TriKind)
- func (t TransposeTri) Untranspose() Matrix
- func (t TransposeTri) UntransposeTri() Triangular
- type TriDense
- func NewTriDense(n int, kind matrix.TriKind, data []float64) *TriDense
- func (t *TriDense) At(i, j int) float64
- func (t *TriDense) Copy(a Matrix) (r, c int)
- func (t *TriDense) Dims() (r, c int)
- func (t *TriDense) InverseTri(a Triangular) error
- func (t *TriDense) LFromCholesky(chol *Cholesky)
- func (t *TriDense) LFromLU(lu *LU)
- func (t *TriDense) MulTri(a, b Triangular)
- func (t *TriDense) RawTriangular() blas64.Triangular
- func (t *TriDense) Reset()
- func (t *TriDense) SetTri(i, j int, v float64)
- func (t *TriDense) T() Matrix
- func (t *TriDense) TTri() Triangular
- func (t *TriDense) Triangle() (n int, kind matrix.TriKind)
- func (t *TriDense) UFromCholesky(chol *Cholesky)
- func (t *TriDense) UFromLU(lu *LU)
- type Triangular
- type UntransposeTrier
- type Untransposer
- type Vector
- func NewVector(n int, data []float64) *Vector
- func (v *Vector) AddScaledVec(a *Vector, alpha float64, b *Vector)
- func (v *Vector) AddVec(a, b *Vector)
- func (v *Vector) At(i, j int) float64
- func (v *Vector) CloneVec(a *Vector)
- func (v *Vector) CopyVec(a *Vector) int
- func (v *Vector) Dims() (r, c int)
- func (v *Vector) DivElemVec(a, b *Vector)
- func (v *Vector) Len() int
- func (v Vector) MarshalBinary() ([]byte, error)
- func (v Vector) MarshalBinaryTo(w io.Writer) (int, error)
- func (v *Vector) MulElemVec(a, b *Vector)
- func (v *Vector) MulVec(a Matrix, b *Vector)
- func (v *Vector) RawVector() blas64.Vector
- func (v *Vector) Reset()
- func (v *Vector) ScaleVec(alpha float64, a *Vector)
- func (v *Vector) SetVec(i int, val float64)
- func (v *Vector) SliceVec(i, k int) *Vector
- func (v *Vector) SolveCholeskyVec(chol *Cholesky, b *Vector) error
- func (v *Vector) SolveLQVec(lq *LQ, trans bool, b *Vector) error
- func (v *Vector) SolveLUVec(lu *LU, trans bool, b *Vector) error
- func (v *Vector) SolveQRVec(qr *QR, trans bool, b *Vector) error
- func (v *Vector) SolveVec(a Matrix, b *Vector) error
- func (v *Vector) SubVec(a, b *Vector)
- func (v *Vector) T() Matrix
- func (v *Vector) UnmarshalBinary(data []byte) error
- func (v *Vector) UnmarshalBinaryFrom(r io.Reader) (int, error)
- func (v *Vector) ViewVec(i, n int) *Vector
- type Viewer
- Bugs

cholesky.go dense.go dense_arithmetic.go doc.go eigen.go format.go gsvd.go hogsvd.go index_no_bound_checks.go inner.go io.go lq.go lu.go matrix.go offset.go pool.go product.go qr.go shadow.go solve.go svd.go symmetric.go triangular.go vector.go

Col copies the elements in the jth column of the matrix into the slice dst. The length of the provided slice must equal the number of rows, unless the slice is nil in which case a new slice is first allocated.

Cond returns the condition number of the given matrix under the given norm. The condition number must be based on the 1-norm, 2-norm or ∞-norm. Cond will panic with matrix.ErrShape if the matrix has zero size.

BUG(btracey): The computation of the 1-norm and ∞-norm for non-square matrices is innacurate, although is typically the right order of magnitude. See https://github.com/xianyi/OpenBLAS/issues/636. While the value returned will change with the resolution of this bug, the result from Cond will match the condition number used internally.

Det returns the determinant of the matrix a. In many expressions using LogDet will be more numerically stable.

Dot returns the sum of the element-wise product of a and b. Dot panics if the matrix sizes are unequal.

Equal returns whether the matrices a and b have the same size and are element-wise equal.

EqualApprox returns whether the matrices a and b have the same size and contain all equal elements with tolerance for element-wise equality specified by epsilon. Matrices with non-equal shapes are not equal.

❖

func Formatted(m Matrix, options ...FormatOption) fmt.Formatter

Formatted returns a fmt.Formatter for the matrix m using the given options.

Code:

a := mat64.NewDense(3, 3, []float64{1, 2, 3, 0, 4, 5, 0, 0, 6}) // Create a matrix formatting value with a prefix and calculating each column // width individually... fa := mat64.Formatted(a, mat64.Prefix(" "), mat64.Squeeze()) // and then print with and without zero value elements. fmt.Printf("with all values:\na = %v\n\n", fa) fmt.Printf("with only non-zero values:\na = % v\n\n", fa) // Modify the matrix... a.Set(0, 2, 0) // and print it without zero value elements. fmt.Printf("after modification with only non-zero values:\na = % v\n\n", fa) // Modify the matrix again... a.Set(0, 2, 123.456) // and print it using scientific notation for large exponents. fmt.Printf("after modification with scientific notation:\na = %.2g\n\n", fa) // See golang.org/pkg/fmt/ floating-point verbs for a comprehensive list.

Output:

with all values: a = ⎡1 2 3⎤ ⎢0 4 5⎥ ⎣0 0 6⎦ with only non-zero values: a = ⎡1 2 3⎤ ⎢. 4 5⎥ ⎣. . 6⎦ after modification with only non-zero values: a = ⎡1 2 .⎤ ⎢. 4 5⎥ ⎣. . 6⎦ after modification with scientific notation: a = ⎡1 2 1.2e+02⎤ ⎢0 4 5⎥ ⎣0 0 6⎦

Inner computes the generalized inner product

x^T A y

between vectors x and y with matrix A. This is only a true inner product if A is symmetric positive definite, though the operation works for any matrix A.

Inner panics if x.Len != m or y.Len != n when A is an m x n matrix.

LogDet returns the log of the determinant and the sign of the determinant for the matrix that has been factorized. Numerical stability in product and division expressions is generally improved by working in log space.

Max returns the largest element value of the matrix A. Max will panic with matrix.ErrShape if the matrix has zero size.

Min returns the smallest element value of the matrix A. Min will panic with matrix.ErrShape if the matrix has zero size.

Norm returns the specified (induced) norm of the matrix a. See https://en.wikipedia.org/wiki/Matrix_norm for the definition of an induced norm.

Valid norms are:

1 - The maximum absolute column sum 2 - Frobenius norm, the square root of the sum of the squares of the elements. Inf - The maximum absolute row sum.

Norm will panic with ErrNormOrder if an illegal norm order is specified and with matrix.ErrShape if the matrix has zero size.

Row copies the elements in the jth column of the matrix into the slice dst. The length of the provided slice must equal the number of columns, unless the slice is nil in which case a new slice is first allocated.

Sum returns the sum of the elements of the matrix.

Trace returns the trace of the matrix. Trace will panic if the matrix is not square.

A BandWidther represents a banded matrix and can return the left and right half-bandwidths, k1 and k2.

❖

```
type Cholesky struct {
// contains filtered or unexported fields
}
```

Cholesky is a type for creating and using the Cholesky factorization of a symmetric positive definite matrix.

Cholesky methods may only be called on a value that has been successfully initialized by a call to Factorize that has returned true. Calls to methods of an unsuccessful Cholesky factorization will panic.

Code:

// Construct a symmetric positive definite matrix. tmp := mat64.NewDense(4, 4, []float64{ 2, 6, 8, -4, 1, 8, 7, -2, 2, 2, 1, 7, 8, -2, -2, 1, }) var a mat64.SymDense a.SymOuterK(1, tmp) fmt.Printf("a = %0.4v\n", mat64.Formatted(&a, mat64.Prefix(" "))) // Compute the cholesky factorization. var chol mat64.Cholesky if ok := chol.Factorize(&a); !ok { fmt.Println("a matrix is not positive semi-definite.") } // Find the determinant. fmt.Printf("\nThe determinant of a is %0.4g\n\n", chol.Det()) // Use the factorization to solve the system of equations a * x = b. b := mat64.NewVector(4, []float64{1, 2, 3, 4}) var x mat64.Vector if err := x.SolveCholeskyVec(&chol, b); err != nil { fmt.Println("Matrix is near singular: ", err) } fmt.Println("Solve a * x = b") fmt.Printf("x = %0.4v\n", mat64.Formatted(&x, mat64.Prefix(" "))) // Extract the factorization and check that it equals the original matrix. var t mat64.TriDense t.LFromCholesky(&chol) var test mat64.Dense test.Mul(&t, t.T()) fmt.Println() fmt.Printf("L * L^T = %0.4v\n", mat64.Formatted(&a, mat64.Prefix(" ")))

Output:

a = ⎡120 114 -4 -16⎤ ⎢114 118 11 -24⎥ ⎢ -4 11 58 17⎥ ⎣-16 -24 17 73⎦ The determinant of a is 1.543e+06 Solve a * x = b x = ⎡ -0.239⎤ ⎢ 0.2732⎥ ⎢-0.04681⎥ ⎣ 0.1031⎦ L * L^T = ⎡120 114 -4 -16⎤ ⎢114 118 11 -24⎥ ⎢ -4 11 58 17⎥ ⎣-16 -24 17 73⎦

Clone makes a copy of the input Cholesky into the receiver, overwriting the previous value of the receiver. Clone does not place any restrictions on receiver shape. Clone panics if the input Cholesky is not the result of a valid decomposition.

Det returns the determinant of the matrix that has been factorized.

Factorize calculates the Cholesky decomposition of the matrix A and returns whether the matrix is positive definite. If Factorize returns false, the factorization must not be used.

LogDet returns the log of the determinant of the matrix that has been factorized.

Reset resets the factorization so that it can be reused as the receiver of a dimensionally restricted operation.

SetFromU sets the Cholesky decomposition from the given triangular matrix. SetFromU panics if t is not upper triangular. Note that t is copied into, not stored inside, the receiver.

Size returns the dimension of the factorized matrix.

SymRankOne performs a rank-1 update of the original matrix A and refactorizes its Cholesky factorization, storing the result into the reciever. That is, if in the original Cholesky factorization

U^T * U = A,

in the updated factorization

U'^T * U' = A + alpha * x * x^T = A'.

Note that when alpha is negative, the updating problem may be ill-conditioned and the results may be inaccurate, or the updated matrix A' may not be positive definite and not have a Cholesky factorization. SymRankOne returns whether the updated matrix A' is positive definite.

SymRankOne updates a Cholesky factorization in O(n²) time. The Cholesky factorization computation from scratch is O(n³).

A Cloner can make a copy of a into the receiver, overwriting the previous value of the receiver. The clone operation does not make any restriction on shape and will not cause shadowing.

A ColViewer can return a Vector reflecting a column that is backed by the matrix data. The Vector returned will have length equal to the number of rows.

A Copier can make a copy of elements of a into the receiver. The submatrix copied starts at row and column 0 and has dimensions equal to the minimum dimensions of the two matrices. The number of row and columns copied is returned. Copy will copy from a source that aliases the receiver unless the source is transposed; an aliasing transpose copy will panic with the exception for a special case when the source data has a unitary increment or stride.

❖

```
type Dense struct {
// contains filtered or unexported fields
}
```

Dense is a dense matrix representation.

DenseCopyOf returns a newly allocated copy of the elements of a.

NewDense creates a new Dense matrix with r rows and c columns. If data == nil, a new slice is allocated for the backing slice. If len(data) == r*c, data is used as the backing slice, and changes to the elements of the returned Dense will be reflected in data. If neither of these is true, NewDense will panic.

The data must be arranged in row-major order, i.e. the (i*c + j)-th element in the data slice is the {i, j}-th element in the matrix.

Add adds a and b element-wise, placing the result in the receiver. Add will panic if the two matrices do not have the same shape.

Apply applies the function fn to each of the elements of a, placing the resulting matrix in the receiver. The function fn takes a row/column index and element value and returns some function of that tuple.

At returns the element at row i, column j.

Augment creates the augmented matrix of a and b, where b is placed in the greater indexed columns. Augment will panic if the two input matrices do not have the same number of rows or the constructed augmented matrix is not the same shape as the receiver.

Caps returns the number of rows and columns in the backing matrix.

Clone makes a copy of a into the receiver, overwriting the previous value of the receiver. The clone operation does not make any restriction on shape and will not cause shadowing.

See the Cloner interface for more information.

ColView returns a Vector reflecting the column j, backed by the matrix data.

See ColViewer for more information.

Copy makes a copy of elements of a into the receiver. It is similar to the built-in copy; it copies as much as the overlap between the two matrices and returns the number of rows and columns it copied. If a aliases the receiver and is a transposed Dense or Vector, with a non-unitary increment, Copy will panic.

See the Copier interface for more information.

Dims returns the number of rows and columns in the matrix.

DivElem performs element-wise division of a by b, placing the result in the receiver. DivElem will panic if the two matrices do not have the same shape.

EigenvectorsSym extracts the eigenvectors of the factorized matrix and stores them in the receiver. Each eigenvector is a column corresponding to the respective eigenvalue returned by e.Values.

EigenvectorsSym panics if the factorization was not successful or if the decomposition did not compute the eigenvectors.

Exp calculates the exponential of the matrix a, e^a, placing the result in the receiver. Exp will panic with matrix.ErrShape if a is not square.

Exp uses the scaling and squaring method described in section 3 of http://www.cs.cornell.edu/cv/researchpdf/19ways+.pdf.

Grow returns the receiver expanded by r rows and c columns. If the dimensions of the expanded matrix are outside the capacities of the receiver a new allocation is made, otherwise not. Note the receiver itself is not modified during the call to Grow.

Inverse computes the inverse of the matrix a, storing the result into the receiver. If a is ill-conditioned, a Condition error will be returned. Note that matrix inversion is numerically unstable, and should generally be avoided where possible, for example by using the Solve routines.

LFromLQ extracts the m×n lower trapezoidal matrix from a LQ decomposition.

MarshalBinary encodes the receiver into a binary form and returns the result.

Dense is little-endian encoded as follows:

0 - 7 number of rows (int64) 8 - 15 number of columns (int64) 16 - .. matrix data elements (float64) [0,0] [0,1] ... [0,ncols-1] [1,0] [1,1] ... [1,ncols-1] ... [nrows-1,0] ... [nrows-1,ncols-1]

MarshalBinaryTo encodes the receiver into a binary form and writes it into w. MarshalBinaryTo returns the number of bytes written into w and an error, if any.

See MarshalBinary for the on-disk layout.

Mul takes the matrix product of a and b, placing the result in the receiver. If the number of columns in a does not equal the number of rows in b, Mul will panic.

MulElem performs element-wise multiplication of a and b, placing the result in the receiver. MulElem will panic if the two matrices do not have the same shape.

Outer calculates the outer product of x and y, and stores the result in the receiver.

m = alpha * x * y'

In order to update an existing matrix, see RankOne.

Permutation constructs an r×r permutation matrix with the given row swaps. A permutation matrix has exactly one element equal to one in each row and column and all other elements equal to zero. swaps[i] specifies the row with which i will be swapped, which is equivalent to the non-zero column of row i.

Pow calculates the integral power of the matrix a to n, placing the result in the receiver. Pow will panic if n is negative or if a is not square.

Product calculates the product of the given factors and places the result in the receiver. The order of multiplication operations is optimized to minimize the number of floating point operations on the basis that all matrix multiplications are general.

QFromGSVD extracts the matrix Q from the singular value decomposition, storing the result in-place into the receiver. Q is size c×c.

QFromLQ extracts the n×n orthonormal matrix Q from an LQ decomposition.

QFromQR extracts the m×m orthonormal matrix Q from a QR decomposition.

RFromQR extracts the m×n upper trapezoidal matrix from a QR decomposition.

RankOne performs a rank-one update to the matrix a and stores the result in the receiver. If a is zero, see Outer.

m = a + alpha * x * y'

RawMatrix returns the underlying blas64.General used by the receiver. Changes to elements in the receiver following the call will be reflected in returned blas64.General.

RawRowView returns a slice backed by the same array as backing the receiver.

Reset zeros the dimensions of the matrix so that it can be reused as the receiver of a dimensionally restricted operation.

See the Reseter interface for more information.

RowView returns row i of the matrix data represented as a column vector, backed by the matrix data.

See RowViewer for more information.

Scale multiplies the elements of a by f, placing the result in the receiver.

See the Scaler interface for more information.

Set sets the element at row i, column j to the value v.

SetCol sets the values in the specified column of the matrix to the values in src. len(src) must equal the number of rows in the receiver.

SetRawMatrix sets the underlying blas64.General used by the receiver. Changes to elements in the receiver following the call will be reflected in b.

SetRow sets the values in the specified rows of the matrix to the values in src. len(src) must equal the number of columns in the receiver.

SigmaAFromGSVD extracts the matrix Σ₁ from the singular value decomposition, storing the result in-place into the receiver. Σ₁ is size r×(k+l).

SigmaBFromGSVD extracts the matrix Σ₂ from the singular value decomposition, storing the result in-place into the receiver. Σ₂ is size p×(k+l).

Slice returns a new Matrix that shares backing data with the receiver. The returned matrix starts at {i,j} of the recevier and extends k-i rows and l-j columns. The final row in the resulting matrix is k-1 and the final column is l-1. Slice panics with ErrIndexOutOfRange if the slice is outside the bounds of the receiver.

Solve finds a minimum-norm solution to a system of linear equations defined by the matrices a and b. If A is singular or near-singular, a Condition error is returned. Please see the documentation for Condition for more information.

The minimization problem solved depends on the input parameters:

- if m >= n, find X such that ||A*X - B||_2 is minimized, - if m < n, find the minimum norm solution of A * X = B.

The solution matrix, X, is stored in-place into the receiver.

SolveCholesky finds the matrix m that solves A * m = b where A is represented by the Cholesky decomposition, placing the result in the receiver.

SolveLQ finds a minimum-norm solution to a system of linear equations defined by the matrices A and b, where A is an m×n matrix represented in its LQ factorized form. If A is singular or near-singular a Condition error is returned. Please see the documentation for Condition for more information.

The minimization problem solved depends on the input parameters.

If trans == false, find the minimum norm solution of A * X = b. If trans == true, find X such that ||A*X - b||_2 is minimized.

The solution matrix, X, is stored in place into the receiver.

SolveLU solves a system of linear equations using the LU decomposition of a matrix. It computes

A * x = b if trans == false A^T * x = b if trans == true

In both cases, A is represented in LU factorized form, and the matrix x is stored into the receiver.

If A is singular or near-singular a Condition error is returned. Please see the documentation for Condition for more information.

SolveQR finds a minimum-norm solution to a system of linear equations defined by the matrices A and b, where A is an m×n matrix represented in its QR factorized form. If A is singular or near-singular a Condition error is returned. Please see the documentation for Condition for more information.

The minimization problem solved depends on the input parameters.

If trans == false, find X such that ||A*X - b||_2 is minimized. If trans == true, find the minimum norm solution of A^T * X = b.

The solution matrix, X, is stored in place into the receiver.

Stack appends the rows of b onto the rows of a, placing the result into the receiver with b placed in the greater indexed rows. Stack will panic if the two input matrices do not have the same number of columns or the constructed stacked matrix is not the same shape as the receiver.

Sub subtracts the matrix b from a, placing the result in the receiver. Sub will panic if the two matrices do not have the same shape.

T performs an implicit transpose by returning the receiver inside a Transpose.

UFromGSVD extracts the matrix U from the singular value decomposition, storing the result in-place into the receiver. U is size r×r.

UFromHOGSVD extracts the matrix U_n from the singular value decomposition, storing the result in-place into the receiver. U_n is size r×c.

UFromHOGSVD will panic if the receiver does not contain a successful factorization.

UFromSVD extracts the matrix U from the singular value decomposition, storing the result in-place into the receiver. U is size m×m if svd.Kind() == SVDFull, of size m×min(m,n) if svd.Kind() == SVDThin, and UFromSVD panics otherwise.

UnmarshalBinary decodes the binary form into the receiver. It panics if the receiver is a non-zero Dense matrix.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- matrix.ErrShape is returned if the number of rows or columns is negative, - an error is returned if the resulting Dense matrix is too big for the current architecture (e.g. a 16GB matrix written by a 64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

UnmarshalBinaryFrom decodes the binary form into the receiver and returns the number of bytes read and an error if any. It panics if the receiver is a non-zero Dense matrix.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- matrix.ErrShape is returned if the number of rows or columns is negative, - an error is returned if the resulting Dense matrix is too big for the current architecture (e.g. a 16GB matrix written by a 64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled matrix, and so it should not be used on untrusted data.

VFromGSVD extracts the matrix V from the singular value decomposition, storing the result in-place into the receiver. V is size p×p.

VFromHOGSVD extracts the matrix V from the singular value decomposition, storing the result in-place into the receiver. V is size c×c.

VFromHOGSVD will panic if the receiver does not contain a successful factorization.

VFromSVD extracts the matrix V from the singular value decomposition, storing the result in-place into the receiver. V is size n×n if svd.Kind() == SVDFull, of size n×min(m,n) if svd.Kind() == SVDThin, and VFromSVD panics otherwise.

View returns a new Matrix that shares backing data with the receiver. The new matrix is located from row i, column j extending r rows and c columns. View panics if the view is outside the bounds of the receiver.

View is deprecated and should not be used. It will be removed at a later date.

ZeroRFromGSVD extracts the matrix [ 0 R ] from the singular value decomposition, storing the result in-place into the receiver. [ 0 R ] is size (k+l)×c.

❖

```
type Eigen struct {
// contains filtered or unexported fields
}
```

Eigen is a type for creating and using the eigenvalue decomposition of a dense matrix.

Factorize computes the eigenvalues of the square matrix a, and optionally the eigenvectors.

A right eigenvalue/eigenvector combination is defined by

A * x_r = λ * x_r

where x_r is the column vector called an eigenvector, and λ is the corresponding eigenvector.

Similarly, a left eigenvalue/eigenvector combination is defined by

x_l * A = λ * x_l

The eigenvalues, but not the eigenvectors, are the same for both decompositions.

Typically eigenvectors refer to right eigenvectors.

In all cases, Eigen computes the eigenvalues of the matrix. If right and left are true, then the right and left eigenvectors will be computed, respectively. Eigen panics if the input matrix is not square.

Factorize returns whether the decomposition succeeded. If the decomposition failed, methods that require a successful factorization will panic.

LeftVectors returns the left eigenvectors of the decomposition. LeftVectors will panic if the left eigenvectors were not computed during the factorization. or if the factorization was not successful.

See the documentation in lapack64.Geev for the format of the vectors.

BUG: This signature and behavior will change when issue #308 is resolved.

❖

func (e *Eigen) Values(dst []complex128) []complex128

Values extracts the eigenvalues of the factorized matrix. If dst is non-nil, the values are stored in-place into dst. In this case dst must have length n, otherwise Values will panic. If dst is nil, then a new slice will be allocated of the proper length and filed with the eigenvalues.

Values panics if the Eigen decomposition was not successful.

Vectors returns the right eigenvectors of the decomposition. Vectors will panic if the right eigenvectors were not computed during the factorization, or if the factorization was not successful.

The returned matrix will contain the right eigenvectors of the decomposition in the columns of the n×n matrix in the same order as their eigenvalues. If the j-th eigenvalue is real, then

u_j = VL[:,j], v_j = VR[:,j],

and if it is not real, then j and j+1 form a complex conjugate pair and the eigenvectors can be recovered as

u_j = VL[:,j] + i*VL[:,j+1], u_{j+1} = VL[:,j] - i*VL[:,j+1], v_j = VR[:,j] + i*VR[:,j+1], v_{j+1} = VR[:,j] - i*VR[:,j+1],

where i is the imaginary unit. The computed eigenvectors are normalized to have Euclidean norm equal to 1 and largest component real.

BUG: This signature and behavior will change when issue #308 is resolved.

❖

```
type EigenSym struct {
// contains filtered or unexported fields
}
```

EigenSym is a type for creating and manipulating the Eigen decomposition of symmetric matrices.

Factorize computes the eigenvalue decomposition of the symmetric matrix a. The Eigen decomposition is defined as

A = P * D * P^-1

where D is a diagonal matrix containing the eigenvalues of the matrix, and P is a matrix of the eigenvectors of A. If the vectors input argument is false, the eigenvectors are not computed.

Factorize returns whether the decomposition succeeded. If the decomposition failed, methods that require a successful factorization will panic.

Values extracts the eigenvalues of the factorized matrix. If dst is non-nil, the values are stored in-place into dst. In this case dst must have length n, otherwise Values will panic. If dst is nil, then a new slice will be allocated of the proper length and filled with the eigenvalues.

Values panics if the Eigen decomposition was not successful.

❖

type FormatOption func(*formatter)

FormatOption is a functional option for matrix formatting.

❖

func DotByte(b byte) FormatOption

DotByte sets the dot character to b. The dot character is used to replace zero elements if the result is printed with the fmt ' ' verb flag. Without a DotByte option, the default dot character is '.'.

❖

func Excerpt(m int) FormatOption

Excerpt sets the maximum number of rows and columns to print at the margins of the matrix to m. If m is zero or less all elements are printed.

Code:

// Excerpt allows diagnostic display of very large // matrices and vectors. // The big matrix is too large to properly print... big := mat64.NewDense(100, 100, nil) for i := 0; i < 100; i++ { big.Set(i, i, 1) } // so only print corner excerpts of the matrix. fmt.Printf("excerpt big identity matrix: %v\n\n", mat64.Formatted(big, mat64.Prefix(" "), mat64.Excerpt(3))) // The long vector is also too large, ... long := mat64.NewVector(100, nil) for i := 0; i < 100; i++ { long.SetVec(i, float64(i)) } // ... so print end excerpts of the vector, fmt.Printf("excerpt long column vector: %v\n\n", mat64.Formatted(long, mat64.Prefix(" "), mat64.Excerpt(3))) // or its transpose. fmt.Printf("excerpt long row vector: %v\n", mat64.Formatted(long.T(), mat64.Prefix(" "), mat64.Excerpt(3)))

Output:

excerpt big identity matrix: Dims(100, 100) ⎡1 0 0 ... ... 0 0 0⎤ ⎢0 1 0 0 0 0⎥ ⎢0 0 1 0 0 0⎥ . . . ⎢0 0 0 1 0 0⎥ ⎢0 0 0 0 1 0⎥ ⎣0 0 0 ... ... 0 0 1⎦ excerpt long column vector: Dims(100, 1) ⎡ 0⎤ ⎢ 1⎥ ⎢ 2⎥ . . . ⎢97⎥ ⎢98⎥ ⎣99⎦ excerpt long row vector: Dims(1, 100) [ 0 1 2 ... ... 97 98 99]

❖

func Prefix(p string) FormatOption

Prefix sets the formatted prefix to the string p. Prefix is a string that is prepended to each line of output.

❖

func Squeeze() FormatOption

Squeeze sets the printing behaviour to minimise column width for each individual column.

❖

```
type GSVD struct {
// contains filtered or unexported fields
}
```

GSVD is a type for creating and using the Generalized Singular Value Decomposition (GSVD) of a matrix. See Factorize for a description of the decomposition.

Factorize computes the generalized singular value decomposition (GSVD) of the input the r×c matrix A and the p×c matrix B. The singular values of A and B are computed in all cases, while the singular vectors are optionally computed depending on the input kind.

The full singular value decomposition (kind == GSVDU|GSVDV|GSVDQ) deconstructs A and B as

A = U * Σ₁ * [ 0 R ] * Q^T B = V * Σ₂ * [ 0 R ] * Q^T

where Σ₁ and Σ₂ are r×(k+l) and p×(k+l) diagonal matrices of singular values, and U, V and Q are r×r, p×p and c×c orthogonal matrices of singular vectors. k+l is the effective numerical rank of the matrix [ A^T B^T ]^T.

It is frequently not necessary to compute the full GSVD. Computation time and storage costs can be reduced using the appropriate kind. Either only the singular values can be computed (kind == SVDNone), or in conjunction with specific singular vectors (kind bit set according to matrix.GSVDU, matrix.GSVDV and matrix.GSVDQ).

Factorize returns whether the decomposition succeeded. If the decomposition failed, routines that require a successful factorization will panic.

GeneralizedValues returns the generalized singular values of the factorized matrices. If the input slice is non-nil, the values will be stored in-place into the slice. In this case, the slice must have length min(r,c)-k, and GeneralizedValues will panic with matrix.ErrSliceLengthMismatch otherwise. If the input slice is nil, a new slice of the appropriate length will be allocated and returned.

GeneralizedValues will panic if the receiver does not contain a successful factorization.

Kind returns the matrix.GSVDKind of the decomposition. If no decomposition has been computed, Kind returns 0.

Rank returns the k and l terms of the rank of [ A^T B^T ]^T.

ValuesA returns the singular values of the factorized A matrix. If the input slice is non-nil, the values will be stored in-place into the slice. In this case, the slice must have length min(r,c)-k, and ValuesA will panic with matrix.ErrSliceLengthMismatch otherwise. If the input slice is nil, a new slice of the appropriate length will be allocated and returned.

ValuesA will panic if the receiver does not contain a successful factorization.

ValuesB returns the singular values of the factorized B matrix. If the input slice is non-nil, the values will be stored in-place into the slice. In this case, the slice must have length min(r,c)-k, and ValuesB will panic with matrix.ErrSliceLengthMismatch otherwise. If the input slice is nil, a new slice of the appropriate length will be allocated and returned.

ValuesB will panic if the receiver does not contain a successful factorization.

A Grower can grow the size of the represented matrix by the given number of rows and columns. Growing beyond the size given by the Caps method will result in the allocation of a new matrix and copying of the elements. If Grow is called with negative increments it will panic with ErrIndexOutOfRange.

❖

```
type HOGSVD struct {
// contains filtered or unexported fields
}
```

HOGSVD is a type for creating and using the Higher Order Generalized Singular Value Decomposition (HOGSVD) of a set of matrices. See Factorize for a description of the decomposition.

Err returns the reason for a factorization failure.

Factorize computes the higher order generalized singular value decomposition (HOGSVD) of the n input r_i×c column tall matrices in m. HOGSV extends the GSVD case from 2 to n input matrices.

M_0 = U_0 * Σ_0 * V^T M_1 = U_1 * Σ_1 * V^T . . . M_{n-1} = U_{n-1} * Σ_{n-1} * V^T

where U_i are r_i×c matrices of singular vectors, Σ are c×c matrices singular values, and V is a c×c matrix of singular vectors.

Factorize returns whether the decomposition succeeded. If the decomposition failed, routines that require a successful factorization will panic.

Len returns the number of matrices that have been factorized. If Len returns zero, the factorization was not successful.

Values returns the nth set of singular values of the factorized system. If the input slice is non-nil, the values will be stored in-place into the slice. In this case, the slice must have length c, and Values will panic with matrix.ErrSliceLengthMismatch otherwise. If the input slice is nil, a new slice of the appropriate length will be allocated and returned.

Values will panic if the receiver does not contain a successful factorization.

❖

```
type LQ struct {
// contains filtered or unexported fields
}
```

LQ is a type for creating and using the LQ factorization of a matrix.

Factorize computes the LQ factorization of an m×n matrix a where n <= m. The LQ factorization always exists even if A is singular.

The LQ decomposition is a factorization of the matrix A such that A = L * Q. The matrix Q is an orthonormal n×n matrix, and L is an m×n upper triangular matrix. L and Q can be extracted from the LFromLQ and QFromLQ methods on Dense.

❖

```
type LU struct {
// contains filtered or unexported fields
}
```

LU is a type for creating and using the LU factorization of a matrix.

Det returns the determinant of the matrix that has been factorized. In many expressions, using LogDet will be more numerically stable.

Factorize computes the LU factorization of the square matrix a and stores the result. The LU decomposition will complete regardless of the singularity of a.

The LU factorization is computed with pivoting, and so really the decomposition is a PLU decomposition where P is a permutation matrix. The individual matrix factors can be extracted from the factorization using the Permutation method on Dense, and the LFrom and UFrom methods on TriDense.

LogDet returns the log of the determinant and the sign of the determinant for the matrix that has been factorized. Numerical stability in product and division expressions is generally improved by working in log space.

Pivot returns pivot indices that enable the construction of the permutation matrix P (see Dense.Permutation). If swaps == nil, then new memory will be allocated, otherwise the length of the input must be equal to the size of the factorized matrix.

RankOne updates an LU factorization as if a rank-one update had been applied to the original matrix A, storing the result into the receiver. That is, if in the original LU decomposition P * L * U = A, in the updated decomposition P * L * U = A + alpha * x * y^T.

Reset resets the factorization so that it can be reused as the receiver of a dimensionally restricted operation.

❖

type Matrix interface { // Dims returns the dimensions of a Matrix. Dims() (r, c int) // At returns the value of a matrix element at row i, column j. // It will panic if i or j are out of bounds for the matrix. At(i, j int) float64 // T returns the transpose of the Matrix. Whether T returns a copy of the // underlying data is implementation dependent. // This method may be implemented using the Transpose type, which // provides an implicit matrix transpose. T() Matrix }

Matrix is the basic matrix interface type.

❖

type Mutable interface { // Set alters the matrix element at row i, column j to v. // It will panic if i or j are out of bounds for the matrix. Set(i, j int, v float64) Matrix }

Mutable is a matrix interface type that allows elements to be altered.

❖

```
type QR struct {
// contains filtered or unexported fields
}
```

QR is a type for creating and using the QR factorization of a matrix.

Factorize computes the QR factorization of an m×n matrix a where m >= n. The QR factorization always exists even if A is singular.

The QR decomposition is a factorization of the matrix A such that A = Q * R. The matrix Q is an orthonormal m×m matrix, and R is an m×n upper triangular matrix. Q and R can be extracted from the QFromQR and RFromQR methods on Dense.

A RawColViewer can return a slice of float64 reflecting a column that is backed by the matrix data.

A RawMatrixSetter can set the underlying blas64.General used by the receiver. There is no restriction on the shape of the receiver. Changes to the receiver's elements will be reflected in the blas64.General.Data.

A RawMatrixer can return a blas64.General representation of the receiver. Changes to the blas64.General.Data slice will be reflected in the original matrix, changes to the Rows, Cols and Stride fields will not.

A RawRowViewer can return a slice of float64 reflecting a row that is backed by the matrix data.

A RawSymmetricer can return a view of itself as a BLAS Symmetric matrix.

❖

type RawTriangular interface { RawTriangular() blas64.Triangular }

A RawVectorer can return a blas64.Vector representation of the receiver. Changes to the blas64.Vector.Data slice will be reflected in the original matrix, changes to the Inc field will not.

❖

```
type Reseter interface {
Reset()
}
```

A Reseter can reset the matrix so that it can be reused as the receiver of a dimensionally restricted operation. This is commonly used when the matrix is being used as a workspace or temporary matrix.

If the matrix is a view, using the reset matrix may result in data corruption in elements outside the view.

A RowViewer can return a Vector reflecting a row that is backed by the matrix data. The Vector returned will have length equal to the number of columns.

❖

```
type SVD struct {
// contains filtered or unexported fields
}
```

SVD is a type for creating and using the Singular Value Decomposition (SVD) of a matrix.

Cond returns the 2-norm condition number for the factorized matrix. Cond will panic if the receiver does not contain a successful factorization.

Factorize computes the singular value decomposition (SVD) of the input matrix A. The singular values of A are computed in all cases, while the singular vectors are optionally computed depending on the input kind.

The full singular value decomposition (kind == SVDFull) deconstructs A as

A = U * Σ * V^T

where Σ is an m×n diagonal matrix of singular vectors, U is an m×m unitary matrix of left singular vectors, and V is an n×n matrix of right singular vectors.

It is frequently not necessary to compute the full SVD. Computation time and storage costs can be reduced using the appropriate kind. Only the singular values can be computed (kind == SVDNone), or a "thin" representation of the singular vectors (kind = SVDThin). The thin representation can save a significant amount of memory if m >> n. See the documentation for the lapack.SVDKind values for more information.

Factorize returns whether the decomposition succeeded. If the decomposition failed, routines that require a successful factorization will panic.

Kind returns the matrix.SVDKind of the decomposition. If no decomposition has been computed, Kind returns 0.

Values returns the singular values of the factorized matrix in decreasing order. If the input slice is non-nil, the values will be stored in-place into the slice. In this case, the slice must have length min(m,n), and Values will panic with matrix.ErrSliceLengthMismatch otherwise. If the input slice is nil, a new slice of the appropriate length will be allocated and returned.

Values will panic if the receiver does not contain a successful factorization.

❖

```
type SymDense struct {
// contains filtered or unexported fields
}
```

SymDense is a symmetric matrix that uses dense storage. SymDense matrices are stored in the upper triangle.

NewSymDense creates a new Symmetric matrix with n rows and columns. If data == nil, a new slice is allocated for the backing slice. If len(data) == n*n, data is used as the backing slice, and changes to the elements of the returned SymDense will be reflected in data. If neither of these is true, NewSymDense will panic.

The data must be arranged in row-major order, i.e. the (i*c + j)-th element in the data slice is the {i, j}-th element in the matrix. Only the values in the upper triangular portion of the matrix are used.

At returns the element at row i and column j.

FromCholesky reconstructs the original positive definite matrix given its Cholesky decomposition.

GrowSquare returns the receiver expanded by n rows and n columns. If the dimensions of the expanded matrix are outside the capacity of the receiver a new allocation is made, otherwise not. Note that the receiver itself is not modified during the call to GrowSquare.

InverseCholesky computes the inverse of the matrix represented by its Cholesky factorization and stores the result into the receiver. If the factorized matrix is ill-conditioned, a Condition error will be returned. Note that matrix inversion is numerically unstable, and should generally be avoided where possible, for example by using the Solve routines.

PowPSD computes a^pow where a is a positive symmetric definite matrix.

PowPSD returns an error if the matrix is not not positive symmetric definite or the Eigendecomposition is not successful.

RankTwo performs a symmmetric rank-two update to the matrix a and stores the result in the receiver

m = a + alpha * (x * y' + y * x')

RawSymmetric returns the matrix as a blas64.Symmetric. The returned value must be stored in upper triangular format.

Reset zeros the dimensions of the matrix so that it can be reused as the receiver of a dimensionally restricted operation.

See the Reseter interface for more information.

ScaleSym multiplies the elements of a by f, placing the result in the receiver.

SetRawSymmetric sets the underlying blas64.Symmetric used by the receiver. Changes to elements in the receiver following the call will be reflected in b. SetRawSymmetric will panic if b is not an upper-encoded symmetric matrix.

SetSym sets the elements at (i,j) and (j,i) to the value v.

SliceSquare returns a new Matrix that shares backing data with the receiver. The returned matrix starts at {i,i} of the recevier and extends k-i rows and columns. The final row and column in the resulting matrix is k-1. SliceSquare panics with ErrIndexOutOfRange if the slice is outside the bounds of the receiver.

SubsetSym extracts a subset of the rows and columns of the matrix a and stores the result in-place into the receiver. The resulting matrix size is len(set)×len(set). Specifically, at the conclusion of SubsetSym, s.At(i, j) equals a.At(set[i], set[j]). Note that the supplied set does not have to be a strict subset, dimension repeats are allowed.

Code:

n := 5 s := mat64.NewSymDense(5, nil) count := 1.0 for i := 0; i < n; i++ { for j := i; j < n; j++ { s.SetSym(i, j, count) count++ } } fmt.Println("Original matrix:") fmt.Printf("%0.4v\n\n", mat64.Formatted(s)) // Take the subset {0, 2, 4} var sub mat64.SymDense sub.SubsetSym(s, []int{0, 2, 4}) fmt.Println("Subset {0, 2, 4}") fmt.Printf("%0.4v\n\n", mat64.Formatted(&sub)) // Take the subset {0, 0, 4} sub.SubsetSym(s, []int{0, 0, 4}) fmt.Println("Subset {0, 0, 4}") fmt.Printf("%0.4v\n\n", mat64.Formatted(&sub))

Output:

Original matrix: ⎡ 1 2 3 4 5⎤ ⎢ 2 6 7 8 9⎥ ⎢ 3 7 10 11 12⎥ ⎢ 4 8 11 13 14⎥ ⎣ 5 9 12 14 15⎦ Subset {0, 2, 4} ⎡ 1 3 5⎤ ⎢ 3 10 12⎥ ⎣ 5 12 15⎦ Subset {0, 0, 4} ⎡ 1 1 5⎤ ⎢ 1 1 5⎥ ⎣ 5 5 15⎦

SymOuterK calculates the outer product of x with itself and stores the result into the receiver. It is equivalent to the matrix multiplication

s = alpha * x * x'.

In order to update an existing matrix, see SymRankOne.

SymRankK performs a symmetric rank-k update to the matrix a and stores the result into the receiver. If a is zero, see SymOuterK.

s = a + alpha * x * x'

SymRankOne performs a symetric rank-one update to the matrix a and stores the result in the receiver

s = a + alpha * x * x'

T implements the Matrix interface. Symmetric matrices, by definition, are equal to their transpose, and this is a no-op.

ViewSquare returns a view of the submatrix starting at {i, i} and extending for n rows and columns. ViewSquare panics if the view is outside the bounds of the receiver.

ViewSquare is deprecated and should not be used. It will be removed at a later date.

❖

type Symmetric interface { Matrix // Symmetric returns the number of rows/columns in the matrix. Symmetric() int }

Symmetric represents a symmetric matrix (where the element at {i, j} equals the element at {j, i}). Symmetric matrices are always square.

Transpose is a type for performing an implicit matrix transpose. It implements the Matrix interface, returning values from the transpose of the matrix within.

At returns the value of the element at row i and column j of the transposed matrix, that is, row j and column i of the Matrix field.

Dims returns the dimensions of the transposed matrix. The number of rows returned is the number of columns in the Matrix field, and the number of columns is the number of rows in the Matrix field.

T performs an implicit transpose by returning the Matrix field.

Untranspose returns the Matrix field.

❖

type TransposeTri struct { Triangular Triangular }

TransposeTri is a type for performing an implicit transpose of a Triangular matrix. It implements the Triangular interface, returning values from the transpose of the matrix within.

❖

func (t TransposeTri) At(i, j int) float64

At returns the value of the element at row i and column j of the transposed matrix, that is, row j and column i of the Triangular field.

❖

func (t TransposeTri) Dims() (r, c int)

Dims returns the dimensions of the transposed matrix. Triangular matrices are square and thus this is the same size as the original Triangular.

❖

func (t TransposeTri) T() Matrix

T performs an implicit transpose by returning the Triangular field.

❖

func (t TransposeTri) TTri() Triangular

TTri performs an implicit transpose by returning the Triangular field.

❖

func (t TransposeTri) Triangle() (int, matrix.TriKind)

Triangle returns the number of rows/columns in the matrix and its orientation.

❖

func (t TransposeTri) Untranspose() Matrix

Untranspose returns the Triangular field.

❖

func (t TransposeTri) UntransposeTri() Triangular

❖

```
type TriDense struct {
// contains filtered or unexported fields
}
```

TriDense represents an upper or lower triangular matrix in dense storage format.

NewTriDense creates a new Triangular matrix with n rows and columns. If data == nil, a new slice is allocated for the backing slice. If len(data) == n*n, data is used as the backing slice, and changes to the elements of the returned TriDense will be reflected in data. If neither of these is true, NewTriDense will panic.

The data must be arranged in row-major order, i.e. the (i*c + j)-th element in the data slice is the {i, j}-th element in the matrix. Only the values in the triangular portion corresponding to kind are used.

At returns the element at row i, column j.

Copy makes a copy of elements of a into the receiver. It is similar to the built-in copy; it copies as much as the overlap between the two matrices and returns the number of rows and columns it copied. Only elements within the receiver's non-zero triangle are set.

See the Copier interface for more information.

❖

func (t *TriDense) InverseTri(a Triangular) error

InverseTri computes the inverse of the triangular matrix a, storing the result into the receiver. If a is ill-conditioned, a Condition error will be returned. Note that matrix inversion is numerically unstable, and should generally be avoided where possible, for example by using the Solve routines.

LFromCholesky extracts the n×n lower triangular matrix L from a Cholesky decomposition

A = L * L^T.

LFromLU extracts the lower triangular matrix from an LU factorization.

❖

func (t *TriDense) MulTri(a, b Triangular)

MulTri takes the product of triangular matrices a and b and places the result in the receiver. The size of a and b must match, and they both must have the same TriKind, or Mul will panic.

❖

func (t *TriDense) RawTriangular() blas64.Triangular

Reset zeros the dimensions of the matrix so that it can be reused as the receiver of a dimensionally restricted operation.

See the Reseter interface for more information.

SetTri sets the element at row i, column j to the value v. It panics if the location is outside the appropriate half of the matrix.

T performs an implicit transpose by returning the receiver inside a Transpose.

❖

func (t *TriDense) TTri() Triangular

TTri performs an implicit transpose by returning the receiver inside a TransposeTri.

Triangle returns the dimension of t and its orientation. The returned orientation is only valid when n is not zero.

UFromCholesky extracts the n×n upper triangular matrix U from a Cholesky decomposition

A = U^T * U.

UFromLU extracts the upper triangular matrix from an LU factorization.

❖

type Triangular interface { Matrix // Triangular returns the number of rows/columns in the matrix and its // orientation. Triangle() (n int, kind matrix.TriKind) // TTri is the equivalent of the T() method in the Matrix interface but // guarantees the transpose is of triangular type. TTri() Triangular }

❖

type UntransposeTrier interface { // Untranspose returns the underlying Triangular stored for the implicit transpose. UntransposeTri() Triangular }

UntransposeTrier is a type that can undo an implicit triangular transpose.

❖

type Untransposer interface { // Untranspose returns the underlying Matrix stored for the implicit transpose. Untranspose() Matrix }

Untransposer is a type that can undo an implicit transpose.

❖

```
type Vector struct {
// contains filtered or unexported fields
}
```

Vector represents a column vector.

NewVector creates a new Vector of length n. If data == nil, a new slice is allocated for the backing slice. If len(data) == n, data is used as the backing slice, and changes to the elements of the returned Vector will be reflected in data. If neither of these is true, NewVector will panic.

AddScaledVec adds the vectors a and alpha*b, placing the result in the receiver.

AddVec adds the vectors a and b, placing the result in the receiver.

At returns the element at row i. It panics if i is out of bounds or if j is not zero.

CloneVec makes a copy of a into the receiver, overwriting the previous value of the receiver.

CopyVec makes a copy of elements of a into the receiver. It is similar to the built-in copy; it copies as much as the overlap between the two vectors and returns the number of elements it copied.

DivElemVec performs element-wise division of a by b, placing the result in the receiver.

Len returns the length of the vector.

MarshalBinary encodes the receiver into a binary form and returns the result.

Vector is little-endian encoded as follows:

0 - 7 number of elements (int64) 8 - .. vector's data elements (float64)

MarshalBinaryTo encodes the receiver into a binary form, writes it to w and returns the number of bytes written and an error if any.

See MarshalBainry for the on-disk format.

MulElemVec performs element-wise multiplication of a and b, placing the result in the receiver.

MulVec computes a * b. The result is stored into the receiver. MulVec panics if the number of columns in a does not equal the number of rows in b.

Reset zeros the length of the vector so that it can be reused as the receiver of a dimensionally restricted operation.

See the Reseter interface for more information.

ScaleVec scales the vector a by alpha, placing the result in the receiver.

SetVec sets the element at row i to the value val. It panics if i is out of bounds.

SliceVec returns a new Vector that shares backing data with the receiver. The returned matrix starts at i of the recevier and extends k-i elements. SliceVec panics with ErrIndexOutOfRange if the slice is outside the bounds of the receiver.

SolveCholeskyVec finds the vector v that solves A * v = b where A is represented by the Cholesky decomposition, placing the result in the receiver.

SolveLQVec finds a minimum-norm solution to a system of linear equations. Please see Dense.SolveLQ for the full documentation.

SolveLUVec solves a system of linear equations using the LU decomposition of a matrix. It computes

A * x = b if trans == false A^T * x = b if trans == true

In both cases, A is represented in LU factorized form, and the matrix x is stored into the receiver.

If A is singular or near-singular a Condition error is returned. Please see the documentation for Condition for more information.

SolveQRVec finds a minimum-norm solution to a system of linear equations. Please see Dense.SolveQR for the full documentation.

SolveVec finds a minimum-norm solution to a system of linear equations defined by the matrix a and the right-hand side vector b. If A is singular or near-singular, a Condition error is returned. Please see the documentation for Dense.Solve for more information.

SubVec subtracts the vector b from a, placing the result in the receiver.

T performs an implicit transpose by returning the receiver inside a Transpose.

UnmarshalBinary decodes the binary form into the receiver. It panics if the receiver is a non-zero Vector.

See MarshalBinary for the on-disk layout.

Limited checks on the validity of the binary input are performed:

- matrix.ErrShape is returned if the number of rows is negative, - an error is returned if the resulting Vector is too big for the current architecture (e.g. a 16GB vector written by a 64b application and read back from a 32b application.)

UnmarshalBinary does not limit the size of the unmarshaled vector, and so it should not be used on untrusted data.

UnmarshalBinaryFrom decodes the binary form into the receiver, from the io.Reader and returns the number of bytes read and an error if any. It panics if the receiver is a non-zero Vector.

See MarshalBinary for the on-disk layout. See UnmarshalBinary for the list of sanity checks performed on the input.

ViewVec returns a sub-vector view of the receiver starting at element i and extending n rows. If i is out of range, n is zero, or the view extends beyond the bounds of the Vector, ViewVec will panic with ErrIndexOutOfRange. The returned Vector retains reference to the underlying vector.

ViewVec is deprecated and should not be used. It will be removed at a later date.

A Viewer returns a submatrix view of the Matrix parameter, starting at row i, column j and extending r rows and c columns. If i or j are out of range, or r or c are zero or extend beyond the bounds of the matrix View will panic with ErrIndexOutOfRange. The returned matrix must retain the receiver's reference to the original matrix such that changes in the elements of the submatrix are reflected in the original and vice versa.

☞ The computation of the 1-norm and ∞-norm for non-square matrices is innacurate, although is typically the right order of magnitude. See https://github.com/xianyi/OpenBLAS/issues/636. While the value returned will change with the resolution of this bug, the result from Cond will match the condition number used internally.

Package mat64 imports 15 packages (graph) and is imported by 273 packages. Updated 2017-04-20. Refresh now. Tools for package owners.