Documentation ¶
Overview ¶
Package mat provides implementations of float64 and complex128 matrix structures and linear algebra operations on them.
Overview ¶
This section provides a quick overview of the mat package. The following sections provide more in depth commentary.
mat provides:
- Interfaces for Matrix classes (Matrix, Symmetric, Triangular)
- Concrete implementations (Dense, SymDense, TriDense, VecDense)
- Methods and functions for using matrix data (Add, Trace, SymRankOne)
- Types for constructing and using matrix factorizations (QR, LU, etc.)
- The complementary types for complex matrices, CMatrix, CSymDense, etc.
In the documentation below, we use "matrix" as a short-hand for all of the FooDense types implemented in this package. We use "Matrix" to refer to the Matrix interface.
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 real matrix of size 3×5 zero := mat.NewDense(3, 5, nil)
If a backing data slice is provided, the matrix will have those elements. All matrices are stored in row-major format and users should consider this when expressing matrix arithmetic to ensure optimal performance.
// Generate a 6×6 matrix of random values. data := make([]float64, 36) for i := range data { data[i] = rand.NormFloat64() } a := mat.NewDense(6, 6, data)
Operations involving matrix data are implemented as functions when the values of the matrix remain unchanged
tr := mat.Trace(a)
and are implemented as methods when the operation modifies the receiver.
zero.Copy(a)
Note that the input arguments to most functions and methods are interfaces rather than concrete types `func Trace(Matrix)` rather than `func Trace(*Dense)` allowing flexible use of internal and external Matrix types.
When a matrix is the destination or receiver for a function or method, the operation will panic if the matrix is not the correct size. An exception to this is when the destination is empty (see below).
Empty matrix ¶
An empty matrix is one that has zero size. Empty matrices are used to allow the destination of a matrix operation to assume the correct size automatically. This operation will re-use the backing data, if available, or will allocate new data if necessary. The IsEmpty method returns whether the given matrix is empty. The zero-value of a matrix is empty, and is useful for easily getting the result of matrix operations.
var c mat.Dense // construct a new zero-value matrix c.Mul(a, a) // c is automatically adjusted to be the right size
The Reset method can be used to revert a matrix to an empty matrix. Reset should not be used when multiple different matrices share the same backing data slice. This can cause unexpected data modifications after being resized. An empty matrix can not be sliced even if it does have an adequately sized backing data slice, but can be expanded using its Grow method if it exists.
The Matrix Interfaces ¶
The Matrix interface is the common link between the concrete types of real matrices. 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 matrix 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 additional interfaces like Symmetric and Triangular. For example, in
func (s *SymDense) AddSym(a, b Symmetric)
the Symmetric interface guarantees a symmetric result.
The CMatrix interface plays the same role for complex matrices. The difference is that the CMatrix type has the H method instead T, for returning the conjugate transpose.
(Conjugate) Transposes
The T method is used for transposition on real matrices, and H is used for conjugate transposition on complex matrices. For example, c.Mul(a.T(), b) computes c = aᵀ * b. The mat types implement this method implicitly — see the Transpose and Conjugate types for more details. Note that some operations have a transpose as part of their definition, as in *SymDense.SymOuterK.
Matrix Factorization ¶
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 mat.LU lu.Factorize(a)
The elements of the factorization can be extracted through methods on the factorized type, for example *LU.UTo. The factorization types can also be used directly, as in *Cholesky.SolveTo. Some factorizations can be updated directly, without needing to update the original matrix and refactorize, for example with *LU.RankOne.
BLAS and LAPACK ¶
BLAS and LAPACK are the standard APIs for linear algebra routines. Many operations in mat are implemented using calls to the wrapper functions in gonum/blas/blas64 and gonum/lapack/lapack64 and their complex equivalents. 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 the wrapper packages' "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.
Type Switching ¶
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 *VecDense 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.
Invariants ¶
Matrix input arguments to package functions are never directly modified. If an operation changes Matrix data, the mutated matrix will be the receiver of a method, or will be the first, dst, argument to a method named with a To suffix.
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()).
Element Aliasing ¶
Most methods in mat 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 mat API, and mat functions will detect and complain about those. There are many ways to make mistakes by excursion from the mat 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.
mat 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 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.
mat will not attempt to detect element overlap if the input does not implement a Raw method. Method behavior is undefined if there is undetected overlap.
Example (UserVectors) ¶
This example shows how simple user types can be constructed to implement basic vector functionality within the mat package.
package main import ( "fmt" "gonum.org/v1/gonum/blas/blas64" "gonum.org/v1/gonum/mat" ) // This example shows how simple user types can be constructed to // implement basic vector functionality within the mat package. func main() { // Perform the cross product of [1 2 3 4] and [1 2 3]. r := row{1, 2, 3, 4} c := column{1, 2, 3} var m mat.Dense m.Mul(c, r) fmt.Println(mat.Formatted(&m)) } // row is a user-defined row vector. type row []float64 // Dims, At and T minimally satisfy the mat.Matrix interface. func (v row) Dims() (r, c int) { return 1, len(v) } func (v row) At(_, j int) float64 { return v[j] } func (v row) T() mat.Matrix { return column(v) } // RawVector allows fast path computation with the vector. func (v row) RawVector() blas64.Vector { return blas64.Vector{N: len(v), Data: v, Inc: 1} } // column is a user-defined column vector. type column []float64 // Dims, At and T minimally satisfy the mat.Matrix interface. func (v column) Dims() (r, c int) { return len(v), 1 } func (v column) At(i, _ int) float64 { return v[i] } func (v column) T() mat.Matrix { return row(v) } // RawVector allows fast path computation with the vector. func (v column) RawVector() blas64.Vector { return blas64.Vector{N: len(v), Data: v, Inc: 1} }
Output: ⎡ 1 2 3 4⎤ ⎢ 2 4 6 8⎥ ⎣ 3 6 9 12⎦
Index ¶
- Constants
- Variables
- func CEqual(a, b CMatrix) bool
- func CEqualApprox(a, b CMatrix, epsilon float64) bool
- 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 Maybe(fn func()) (err error)
- func MaybeComplex(fn func() complex128) (f complex128, err error)
- func MaybeFloat(fn func() float64) (f float64, err error)
- 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 BandCholesky
- func (ch *BandCholesky) At(i, j int) float64
- func (ch *BandCholesky) Bandwidth() (kl, ku int)
- func (ch *BandCholesky) Cond() float64
- func (ch *BandCholesky) Det() float64
- func (ch *BandCholesky) Dims() (r, c int)
- func (ch *BandCholesky) Factorize(a SymBanded) (ok bool)
- func (ch *BandCholesky) IsEmpty() bool
- func (ch *BandCholesky) LogDet() float64
- func (ch *BandCholesky) Reset()
- func (ch *BandCholesky) SolveTo(dst *Dense, b Matrix) error
- func (ch *BandCholesky) SolveVecTo(dst *VecDense, b Vector) error
- func (ch *BandCholesky) SymBand() (n, k int)
- func (ch *BandCholesky) Symmetric() int
- func (ch *BandCholesky) T() Matrix
- func (ch *BandCholesky) TBand() Banded
- type BandDense
- func (b *BandDense) At(i, j int) float64
- func (b *BandDense) Bandwidth() (kl, ku int)
- func (b *BandDense) DiagView() Diagonal
- func (b *BandDense) Dims() (r, c int)
- func (b *BandDense) DoColNonZero(j int, fn func(i, j int, v float64))
- func (b *BandDense) DoNonZero(fn func(i, j int, v float64))
- func (b *BandDense) DoRowNonZero(i int, fn func(i, j int, v float64))
- func (b *BandDense) IsEmpty() bool
- func (b *BandDense) MulVecTo(dst *VecDense, trans bool, x Vector)
- func (b *BandDense) RawBand() blas64.Band
- func (b *BandDense) Reset()
- func (b *BandDense) SetBand(i, j int, v float64)
- func (b *BandDense) SetRawBand(mat blas64.Band)
- func (b *BandDense) T() Matrix
- func (b *BandDense) TBand() Banded
- func (b *BandDense) Trace() float64
- func (b *BandDense) Zero()
- type BandWidther
- type Banded
- type CDense
- func (m *CDense) At(i, j int) complex128
- func (m *CDense) Caps() (r, c int)
- func (m *CDense) Conj(a CMatrix)
- func (m *CDense) Copy(a CMatrix) (r, c int)
- func (m *CDense) Dims() (r, c int)
- func (m *CDense) Grow(r, c int) CMatrix
- func (m *CDense) H() CMatrix
- func (m *CDense) IsEmpty() bool
- func (m *CDense) RawCMatrix() cblas128.General
- func (m *CDense) Reset()
- func (m *CDense) ReuseAs(r, c int)
- func (m *CDense) Set(i, j int, v complex128)
- func (m *CDense) SetRawCMatrix(b cblas128.General)
- func (m *CDense) Slice(i, k, j, l int) CMatrix
- func (m *CDense) T() CMatrix
- func (m *CDense) Zero()
- type CMatrix
- type CTranspose
- type CUntransposer
- type Cholesky
- func (c *Cholesky) At(i, j int) float64
- func (c *Cholesky) Clone(chol *Cholesky)
- func (c *Cholesky) Cond() float64
- func (c *Cholesky) Det() float64
- func (ch *Cholesky) Dims() (r, c int)
- func (c *Cholesky) ExtendVecSym(a *Cholesky, v Vector) (ok bool)
- func (c *Cholesky) Factorize(a Symmetric) (ok bool)
- func (c *Cholesky) InverseTo(dst *SymDense) error
- func (c *Cholesky) IsEmpty() bool
- func (c *Cholesky) LTo(dst *TriDense)
- func (c *Cholesky) LogDet() float64
- func (c *Cholesky) RawU() Triangular
- func (c *Cholesky) Reset()
- func (c *Cholesky) Scale(f float64, orig *Cholesky)
- func (c *Cholesky) SetFromU(t Triangular)
- func (a *Cholesky) SolveCholTo(dst *Dense, b *Cholesky) error
- func (c *Cholesky) SolveTo(dst *Dense, b Matrix) error
- func (c *Cholesky) SolveVecTo(dst *VecDense, b Vector) error
- func (c *Cholesky) SymRankOne(orig *Cholesky, alpha float64, x Vector) (ok bool)
- func (c *Cholesky) Symmetric() int
- func (c *Cholesky) T() Matrix
- func (c *Cholesky) ToSym(dst *SymDense)
- func (c *Cholesky) UTo(dst *TriDense)
- type ClonerFrom
- type ColNonZeroDoer
- type ColViewer
- type Condition
- type ConjTranspose
- type Copier
- type 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) CloneFrom(a Matrix)
- func (m *Dense) ColView(j int) Vector
- func (m *Dense) Copy(a Matrix) (r, c int)
- func (m *Dense) DiagView() Diagonal
- func (m *Dense) Dims() (r, c int)
- func (m *Dense) DivElem(a, b Matrix)
- func (m *Dense) Exp(a Matrix)
- func (m *Dense) Grow(r, c int) Matrix
- func (m *Dense) Inverse(a Matrix) error
- func (m *Dense) IsEmpty() bool
- func (m *Dense) Kronecker(a, b Matrix)
- 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) 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) ReuseAs(r, c int)
- 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) Slice(i, k, j, l int) Matrix
- func (m *Dense) Solve(a, 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) Trace() float64
- func (m *Dense) UnmarshalBinary(data []byte) error
- func (m *Dense) UnmarshalBinaryFrom(r io.Reader) (int, error)
- func (m *Dense) Zero()
- type DiagDense
- func (d *DiagDense) At(i, j int) float64
- func (d *DiagDense) Bandwidth() (kl, ku int)
- func (d *DiagDense) Diag() int
- func (d *DiagDense) DiagFrom(m Matrix)
- func (d *DiagDense) DiagView() Diagonal
- func (d *DiagDense) Dims() (r, c int)
- func (d *DiagDense) IsEmpty() bool
- func (d *DiagDense) RawBand() blas64.Band
- func (d *DiagDense) RawSymBand() blas64.SymmetricBand
- func (d *DiagDense) Reset()
- func (d *DiagDense) SetDiag(i int, v float64)
- func (d *DiagDense) SymBand() (n, k int)
- func (d *DiagDense) Symmetric() int
- func (d *DiagDense) T() Matrix
- func (d *DiagDense) TBand() Banded
- func (d *DiagDense) TTri() Triangular
- func (d *DiagDense) TTriBand() TriBanded
- func (d *DiagDense) Trace() float64
- func (d *DiagDense) TriBand() (n, k int, kind TriKind)
- func (d *DiagDense) Triangle() (int, TriKind)
- func (d *DiagDense) Zero()
- type Diagonal
- type Eigen
- type EigenKind
- type EigenSym
- type Error
- type ErrorStack
- type FormatOption
- type GSVD
- func (gsvd *GSVD) Factorize(a, b Matrix, kind GSVDKind) (ok bool)
- func (gsvd *GSVD) GeneralizedValues(v []float64) []float64
- func (gsvd *GSVD) Kind() GSVDKind
- func (gsvd *GSVD) QTo(dst *Dense)
- func (gsvd *GSVD) Rank() (k, l int)
- func (gsvd *GSVD) SigmaATo(dst *Dense)
- func (gsvd *GSVD) SigmaBTo(dst *Dense)
- func (gsvd *GSVD) UTo(dst *Dense)
- func (gsvd *GSVD) VTo(dst *Dense)
- func (gsvd *GSVD) ValuesA(s []float64) []float64
- func (gsvd *GSVD) ValuesB(s []float64) []float64
- func (gsvd *GSVD) ZeroRTo(dst *Dense)
- type GSVDKind
- type Grower
- type HOGSVD
- type LQ
- type LU
- func (lu *LU) Cond() float64
- func (lu *LU) Det() float64
- func (lu *LU) Factorize(a Matrix)
- func (lu *LU) LTo(dst *TriDense) *TriDense
- 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()
- func (lu *LU) SolveTo(dst *Dense, trans bool, b Matrix) error
- func (lu *LU) SolveVecTo(dst *VecDense, trans bool, b Vector) error
- func (lu *LU) UTo(dst *TriDense)
- type Matrix
- type Mutable
- type MutableBanded
- type MutableDiagonal
- type MutableSymBanded
- type MutableSymmetric
- type MutableTriBanded
- type MutableTriangular
- type MutableVector
- type NonZeroDoer
- type QR
- type RawBander
- type RawCMatrixer
- type RawColViewer
- type RawMatrixSetter
- type RawMatrixer
- type RawRowViewer
- type RawSymBander
- type RawSymmetricer
- type RawTriBander
- type RawTriangular
- type RawVectorer
- type Reseter
- type RowNonZeroDoer
- type RowViewer
- type SVD
- func (svd *SVD) Cond() float64
- func (svd *SVD) Factorize(a Matrix, kind SVDKind) (ok bool)
- func (svd *SVD) Kind() SVDKind
- func (svd *SVD) Rank(rcond float64) int
- func (svd *SVD) SolveTo(dst *Dense, b Matrix, rank int) []float64
- func (svd *SVD) SolveVecTo(dst *VecDense, b Vector, rank int) float64
- func (svd *SVD) UTo(dst *Dense)
- func (svd *SVD) VTo(dst *Dense)
- func (svd *SVD) Values(s []float64) []float64
- type SVDKind
- type SymBandDense
- func (s *SymBandDense) At(i, j int) float64
- func (s *SymBandDense) Bandwidth() (kl, ku int)
- func (s *SymBandDense) DiagView() Diagonal
- func (s *SymBandDense) Dims() (r, c int)
- func (s *SymBandDense) DoColNonZero(j int, fn func(i, j int, v float64))
- func (s *SymBandDense) DoNonZero(fn func(i, j int, v float64))
- func (s *SymBandDense) DoRowNonZero(i int, fn func(i, j int, v float64))
- func (s *SymBandDense) IsEmpty() bool
- func (s *SymBandDense) MulVecTo(dst *VecDense, _ bool, x Vector)
- func (s *SymBandDense) RawSymBand() blas64.SymmetricBand
- func (s *SymBandDense) Reset()
- func (s *SymBandDense) SetRawSymBand(mat blas64.SymmetricBand)
- func (s *SymBandDense) SetSymBand(i, j int, v float64)
- func (s *SymBandDense) SymBand() (n, k int)
- func (s *SymBandDense) Symmetric() int
- func (s *SymBandDense) T() Matrix
- func (s *SymBandDense) TBand() Banded
- func (s *SymBandDense) Trace() float64
- func (s *SymBandDense) Zero()
- type SymBanded
- type SymDense
- func (s *SymDense) AddSym(a, b Symmetric)
- func (s *SymDense) At(i, j int) float64
- func (s *SymDense) Caps() (r, c int)
- func (s *SymDense) CopySym(a Symmetric) int
- func (s *SymDense) DiagView() Diagonal
- func (s *SymDense) Dims() (r, c int)
- func (s *SymDense) GrowSym(n int) Symmetric
- func (s *SymDense) IsEmpty() bool
- 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) ReuseAsSym(n int)
- func (s *SymDense) ScaleSym(f float64, a Symmetric)
- func (s *SymDense) SetRawSymmetric(mat blas64.Symmetric)
- func (s *SymDense) SetSym(i, j int, v float64)
- func (s *SymDense) SliceSym(i, k int) Symmetric
- 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) Trace() float64
- func (s *SymDense) Zero()
- type Symmetric
- type Tracer
- type Transpose
- type TransposeBand
- type TransposeTri
- type TransposeTriBand
- func (t TransposeTriBand) At(i, j int) float64
- func (t TransposeTriBand) Bandwidth() (kl, ku int)
- func (t TransposeTriBand) Dims() (r, c int)
- func (t TransposeTriBand) T() Matrix
- func (t TransposeTriBand) TBand() Banded
- func (t TransposeTriBand) TTri() Triangular
- func (t TransposeTriBand) TTriBand() TriBanded
- func (t TransposeTriBand) TriBand() (n, k int, kind TriKind)
- func (t TransposeTriBand) Triangle() (int, TriKind)
- func (t TransposeTriBand) Untranspose() Matrix
- func (t TransposeTriBand) UntransposeBand() Banded
- func (t TransposeTriBand) UntransposeTri() Triangular
- func (t TransposeTriBand) UntransposeTriBand() TriBanded
- type TransposeVec
- func (t TransposeVec) At(i, j int) float64
- func (t TransposeVec) AtVec(i int) float64
- func (t TransposeVec) Dims() (r, c int)
- func (t TransposeVec) Len() int
- func (t TransposeVec) T() Matrix
- func (t TransposeVec) TVec() Vector
- func (t TransposeVec) Untranspose() Matrix
- func (t TransposeVec) UntransposeVec() Vector
- type TriBandDense
- func (t *TriBandDense) At(i, j int) float64
- func (t *TriBandDense) Bandwidth() (kl, ku int)
- func (t *TriBandDense) DiagView() Diagonal
- func (t *TriBandDense) Dims() (r, c int)
- func (t *TriBandDense) IsEmpty() bool
- func (t *TriBandDense) RawTriBand() blas64.TriangularBand
- func (t *TriBandDense) Reset()
- func (t *TriBandDense) ReuseAsTriBand(n, k int, kind TriKind)
- func (t *TriBandDense) SetRawTriBand(mat blas64.TriangularBand)
- func (t *TriBandDense) SetTriBand(i, j int, v float64)
- func (t *TriBandDense) SolveTo(dst *Dense, trans bool, b Matrix) error
- func (t *TriBandDense) SolveVecTo(dst *VecDense, trans bool, b Vector) error
- func (t *TriBandDense) T() Matrix
- func (t *TriBandDense) TBand() Banded
- func (t *TriBandDense) TTri() Triangular
- func (t *TriBandDense) TTriBand() TriBanded
- func (t *TriBandDense) Trace() float64
- func (t *TriBandDense) TriBand() (n, k int, kind TriKind)
- func (t *TriBandDense) Triangle() (n int, kind TriKind)
- func (t *TriBandDense) Zero()
- type TriBanded
- type TriDense
- func (t *TriDense) At(i, j int) float64
- func (t *TriDense) Copy(a Matrix) (r, c int)
- func (t *TriDense) DiagView() Diagonal
- func (t *TriDense) Dims() (r, c int)
- func (t *TriDense) DoColNonZero(j int, fn func(i, j int, v float64))
- func (t *TriDense) DoNonZero(fn func(i, j int, v float64))
- func (t *TriDense) DoRowNonZero(i int, fn func(i, j int, v float64))
- func (t *TriDense) InverseTri(a Triangular) error
- func (t *TriDense) IsEmpty() bool
- func (t *TriDense) MulTri(a, b Triangular)
- func (t *TriDense) RawTriangular() blas64.Triangular
- func (t *TriDense) Reset()
- func (t *TriDense) ReuseAsTri(n int, kind TriKind)
- func (t *TriDense) ScaleTri(f float64, a Triangular)
- func (t *TriDense) SetRawTriangular(mat blas64.Triangular)
- func (t *TriDense) SetTri(i, j int, v float64)
- func (t *TriDense) SliceTri(i, k int) Triangular
- func (t *TriDense) T() Matrix
- func (t *TriDense) TTri() Triangular
- func (t *TriDense) Trace() float64
- func (t *TriDense) Triangle() (n int, kind TriKind)
- func (t *TriDense) Zero()
- type TriKind
- type Triangular
- type UnConjTransposer
- type UntransposeBander
- type UntransposeTriBander
- type UntransposeTrier
- type Untransposer
- type VecDense
- func (v *VecDense) AddScaledVec(a Vector, alpha float64, b Vector)
- func (v *VecDense) AddVec(a, b Vector)
- func (v *VecDense) At(i, j int) float64
- func (v *VecDense) AtVec(i int) float64
- func (v *VecDense) Cap() int
- func (v *VecDense) Caps() (r, c int)
- func (v *VecDense) CloneFromVec(a Vector)
- func (v *VecDense) ColViewOf(m RawMatrixer, j int)
- func (v *VecDense) CopyVec(a Vector) int
- func (v *VecDense) Dims() (r, c int)
- func (v *VecDense) DivElemVec(a, b Vector)
- func (v *VecDense) IsEmpty() bool
- func (v *VecDense) Len() int
- func (v VecDense) MarshalBinary() ([]byte, error)
- func (v VecDense) MarshalBinaryTo(w io.Writer) (int, error)
- func (v *VecDense) MulElemVec(a, b Vector)
- func (v *VecDense) MulVec(a Matrix, b Vector)
- func (v *VecDense) RawVector() blas64.Vector
- func (v *VecDense) Reset()
- func (v *VecDense) ReuseAsVec(n int)
- func (v *VecDense) RowViewOf(m RawMatrixer, i int)
- func (v *VecDense) ScaleVec(alpha float64, a Vector)
- func (v *VecDense) SetRawVector(a blas64.Vector)
- func (v *VecDense) SetVec(i int, val float64)
- func (v *VecDense) SliceVec(i, k int) Vector
- func (v *VecDense) SolveVec(a Matrix, b Vector) error
- func (v *VecDense) SubVec(a, b Vector)
- func (v *VecDense) T() Matrix
- func (v *VecDense) TVec() Vector
- func (v *VecDense) UnmarshalBinary(data []byte) error
- func (v *VecDense) UnmarshalBinaryFrom(r io.Reader) (int, error)
- func (v *VecDense) Zero()
- type Vector
- Bugs
Examples ¶
Constants ¶
const ( // CondNorm is the matrix norm used for computing the condition number by routines // in the matrix packages. CondNorm = lapack.MaxRowSum // CondNormTrans is the norm used to compute on Aᵀ to get the same result as // computing CondNorm on A. CondNormTrans = lapack.MaxColumnSum )
const ConditionTolerance = 1e16
ConditionTolerance is the tolerance limit of the condition number. If the condition number is above this value, the matrix is considered singular.
Variables ¶
var ( ErrNegativeDimension = Error{"mat: negative dimension"} ErrIndexOutOfRange = Error{"mat: index out of range"} ErrReuseNonEmpty = Error{"mat: reuse of non-empty matrix"} ErrRowAccess = Error{"mat: row index out of range"} ErrColAccess = Error{"mat: column index out of range"} ErrVectorAccess = Error{"mat: vector index out of range"} ErrZeroLength = Error{"mat: zero length in matrix dimension"} ErrRowLength = Error{"mat: row length mismatch"} ErrColLength = Error{"mat: col length mismatch"} ErrSquare = Error{"mat: expect square matrix"} ErrNormOrder = Error{"mat: invalid norm order for matrix"} ErrSingular = Error{"mat: matrix is singular"} ErrShape = Error{"mat: dimension mismatch"} ErrIllegalStride = Error{"mat: illegal stride"} ErrPivot = Error{"mat: malformed pivot list"} ErrTriangle = Error{"mat: triangular storage mismatch"} ErrTriangleSet = Error{"mat: triangular set out of bounds"} ErrBandwidth = Error{"mat: bandwidth out of range"} ErrBandSet = Error{"mat: band set out of bounds"} ErrDiagSet = Error{"mat: diagonal set out of bounds"} ErrSliceLengthMismatch = Error{"mat: input slice length mismatch"} ErrNotPSD = Error{"mat: input not positive symmetric definite"} ErrFailedEigen = Error{"mat: eigendecomposition not successful"} )
Functions ¶
func CEqual ¶
CEqual returns whether the matrices a and b have the same size and are element-wise equal.
func CEqualApprox ¶
CEqualApprox 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 Col ¶
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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // This example copies the second column of a matrix into col, allocating a new slice of float64. m := mat.NewDense(3, 3, []float64{ 2.0, 9.0, 3.0, 4.5, 6.7, 8.0, 1.2, 3.0, 6.0, }) col := mat.Col(nil, 1, m) fmt.Printf("col = %#v", col) }
Output: col = []float64{9, 6.7, 3}
func Cond ¶
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 inaccurate, 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.
func Det ¶
Det returns the determinant of the matrix a. In many expressions using LogDet will be more numerically stable.
func Dot ¶
Dot returns the sum of the element-wise product of a and b. Dot panics if the matrix sizes are unequal.
func Equal ¶
Equal returns whether the matrices a and b have the same size and are element-wise equal.
func EqualApprox ¶
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 ¶
func Formatted(m Matrix, options ...FormatOption) fmt.Formatter
Formatted returns a fmt.Formatter for the matrix m using the given options.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { a := mat.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 := mat.Formatted(a, mat.Prefix(" "), mat.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⎦
Example (MATLAB) ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { a := mat.NewDense(3, 3, []float64{1, 2, 3, 0, 4, 5, 0, 0, 6}) // Create a matrix formatting value using MATLAB format... fa := mat.Formatted(a, mat.FormatMATLAB()) // and then print with and without layout formatting. fmt.Printf("standard syntax:\na = %v\n\n", fa) fmt.Printf("layout syntax:\na = %#v\n\n", fa) }
Output: standard syntax: a = [1 2 3; 0 4 5; 0 0 6] layout syntax: a = [ 1 2 3 0 4 5 0 0 6 ]
Example (Python) ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { a := mat.NewDense(3, 3, []float64{1, 2, 3, 0, 4, 5, 0, 0, 6}) // Create a matrix formatting value with a prefix using Python format... fa := mat.Formatted(a, mat.Prefix(" "), mat.FormatPython()) // and then print with and without layout formatting. fmt.Printf("standard syntax:\na = %v\n\n", fa) fmt.Printf("layout syntax:\na = %#v\n\n", fa) }
Output: standard syntax: a = [[1, 2, 3], [0, 4, 5], [0, 0, 6]] layout syntax: a = [[1, 2, 3], [0, 4, 5], [0, 0, 6]]
func Inner ¶
Inner computes the generalized inner product
xᵀ A y
between the vectors x and y with matrix A, where x and y are treated as column vectors.
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.
func LogDet ¶
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.
func Max ¶
Max returns the largest element value of the matrix A. Max will panic with matrix.ErrShape if the matrix has zero size.
func Maybe ¶
func Maybe(fn func()) (err error)
Maybe will recover a panic with a type mat.Error from fn, and return this error as the Err field of an ErrorStack. The stack trace for the panicking function will be recovered and placed in the StackTrace field. Any other error is re-panicked.
func MaybeComplex ¶
func MaybeComplex(fn func() complex128) (f complex128, err error)
MaybeComplex will recover a panic with a type mat.Error from fn, and return this error as the Err field of an ErrorStack. The stack trace for the panicking function will be recovered and placed in the StackTrace field. Any other error is re-panicked.
func MaybeFloat ¶
MaybeFloat will recover a panic with a type mat.Error from fn, and return this error as the Err field of an ErrorStack. The stack trace for the panicking function will be recovered and placed in the StackTrace field. Any other error is re-panicked.
func Min ¶
Min returns the smallest element value of the matrix A. Min will panic with matrix.ErrShape if the matrix has zero size.
func Norm ¶
Norm returns the specified norm of the matrix A. Valid norms are:
1 - The maximum absolute column sum 2 - The 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 ErrShape if the matrix has zero size.
func Row ¶
Row copies the elements in the ith row 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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // This example copies the third row of a matrix into row, allocating a new slice of float64. m := mat.NewDense(3, 3, []float64{ 2.0, 9.0, 3.0, 4.5, 6.7, 8.0, 1.2, 3.0, 6.0, }) row := mat.Row(nil, 2, m) fmt.Printf("row = %#v", row) }
Output: row = []float64{1.2, 3, 6}
Types ¶
type BandCholesky ¶
type BandCholesky struct {
// contains filtered or unexported fields
}
BandCholesky is a symmetric positive-definite band matrix represented by its Cholesky decomposition.
Note that this matrix representation is useful for certain operations, in particular finding solutions to linear equations. It is very inefficient at other operations, in particular At is slow.
BandCholesky 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.
func (*BandCholesky) At ¶
func (ch *BandCholesky) At(i, j int) float64
At returns the element at row i, column j.
func (*BandCholesky) Bandwidth ¶
func (ch *BandCholesky) Bandwidth() (kl, ku int)
Bandwidth returns the lower and upper bandwidth values for the matrix. The total bandwidth of the matrix is kl+ku+1.
func (*BandCholesky) Cond ¶
func (ch *BandCholesky) Cond() float64
Cond returns the condition number of the factorized matrix.
func (*BandCholesky) Det ¶
func (ch *BandCholesky) Det() float64
Det returns the determinant of the matrix that has been factorized.
func (*BandCholesky) Dims ¶
func (ch *BandCholesky) Dims() (r, c int)
Dims returns the dimensions of the matrix.
func (*BandCholesky) Factorize ¶
func (ch *BandCholesky) Factorize(a SymBanded) (ok bool)
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.
func (*BandCholesky) IsEmpty ¶
func (ch *BandCholesky) IsEmpty() bool
IsEmpty returns whether the receiver is empty. Empty matrices can be the receiver for dimensionally restricted operations. The receiver can be emptied using Reset.
func (*BandCholesky) LogDet ¶
func (ch *BandCholesky) LogDet() float64
LogDet returns the log of the determinant of the matrix that has been factorized.
func (*BandCholesky) Reset ¶
func (ch *BandCholesky) Reset()
Reset resets the factorization so that it can be reused as the receiver of a dimensionally restricted operation.
func (*BandCholesky) SolveTo ¶
func (ch *BandCholesky) SolveTo(dst *Dense, b Matrix) error
SolveTo finds the matrix X that solves A * X = B where A is represented by the Cholesky decomposition. The result is stored in-place into dst. If the Cholesky decomposition is singular or near-singular a Condition error is returned. See the documentation for Condition for more information.
func (*BandCholesky) SolveVecTo ¶
func (ch *BandCholesky) SolveVecTo(dst *VecDense, b Vector) error
SolveVecTo finds the vector x that solves A * x = b where A is represented by the Cholesky decomposition. The result is stored in-place into dst. If the Cholesky decomposition is singular or near-singular a Condition error is returned. See the documentation for Condition for more information.
func (*BandCholesky) SymBand ¶
func (ch *BandCholesky) SymBand() (n, k int)
SymBand returns the number of rows/columns in the matrix, and the size of the bandwidth. The total bandwidth of the matrix is 2*k+1.
func (*BandCholesky) Symmetric ¶
func (ch *BandCholesky) Symmetric() int
Symmetric implements the Symmetric interface and returns the number of rows in the matrix (this is also the number of columns).
func (*BandCholesky) T ¶
func (ch *BandCholesky) T() Matrix
T returns the receiver, the transpose of a symmetric matrix.
func (*BandCholesky) TBand ¶
func (ch *BandCholesky) TBand() Banded
TBand returns the receiver, the transpose of a symmetric band matrix.
type BandDense ¶
type BandDense struct {
// contains filtered or unexported fields
}
BandDense represents a band matrix in dense storage format.
func NewBandDense ¶
NewBandDense creates a new Band matrix with r rows and c columns. If data == nil, a new slice is allocated for the backing slice. If len(data) == min(r, c+kl)*(kl+ku+1), data is used as the backing slice, and changes to the elements of the returned BandDense will be reflected in data. If neither of these is true, NewBandDense will panic. kl must be at least zero and less r, and ku must be at least zero and less than c, otherwise NewBandDense will panic. NewBandDense will panic if either r or c is zero.
The data must be arranged in row-major order constructed by removing the zeros from the rows outside the band and aligning the diagonals. For example, the matrix
1 2 3 0 0 0 4 5 6 7 0 0 0 8 9 10 11 0 0 0 12 13 14 15 0 0 0 16 17 18 0 0 0 0 19 20
becomes (* entries are never accessed)
- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 * 19 20 * *
which is passed to NewBandDense as []float64{*, 1, 2, 3, 4, ...} with kl=1 and ku=2. Only the values in the band portion of the matrix are used.
func NewDiagonalRect ¶
NewDiagonalRect is a convenience function that returns a diagonal matrix represented by a BandDense. The length of data must be min(r, c) otherwise NewDiagonalRect will panic.
func (*BandDense) DoColNonZero ¶
DoColNonZero calls the function fn for each of the non-zero elements of column j of b. The function fn takes a row/column index and the element value of b at (i, j).
func (*BandDense) DoNonZero ¶
DoNonZero calls the function fn for each of the non-zero elements of b. The function fn takes a row/column index and the element value of b at (i, j).
func (*BandDense) DoRowNonZero ¶
DoRowNonZero calls the function fn for each of the non-zero elements of row i of b. The function fn takes a row/column index and the element value of b at (i, j).
func (*BandDense) IsEmpty ¶
IsEmpty returns whether the receiver is empty. Empty matrices can be the receiver for size-restricted operations. The receiver can be zeroed using Reset.
func (*BandDense) RawBand ¶
RawBand returns the underlying blas64.Band used by the receiver. Changes to elements in the receiver following the call will be reflected in returned blas64.Band.
func (*BandDense) Reset ¶
func (b *BandDense) Reset()
Reset empties the matrix so that it can be reused as the receiver of a dimensionally restricted operation.
Reset should not be used when the matrix shares backing data. See the Reseter interface for more information.
func (*BandDense) SetBand ¶
SetBand sets the element at row i, column j to the value v. It panics if the location is outside the appropriate region of the matrix.
func (*BandDense) SetRawBand ¶
SetRawBand sets the underlying blas64.Band used by the receiver. Changes to elements in the receiver following the call will be reflected in the input.
func (*BandDense) T ¶
T performs an implicit transpose by returning the receiver inside a Transpose.
func (*BandDense) TBand ¶
TBand performs an implicit transpose by returning the receiver inside a TransposeBand.
type BandWidther ¶
type BandWidther interface {
BandWidth() (k1, k2 int)
}
A BandWidther represents a banded matrix and can return the left and right half-bandwidths, k1 and k2.
type Banded ¶
type Banded interface { Matrix // Bandwidth returns the lower and upper bandwidth values for // the matrix. The total bandwidth of the matrix is kl+ku+1. Bandwidth() (kl, ku int) // TBand is the equivalent of the T() method in the Matrix // interface but guarantees the transpose is of banded type. TBand() Banded }
Banded is a band matrix representation.
type CDense ¶
type CDense struct {
// contains filtered or unexported fields
}
CDense is a dense matrix representation with complex data.
func NewCDense ¶
func NewCDense(r, c int, data []complex128) *CDense
NewCDense creates a new complex 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 CDense will be reflected in data. If neither of these is true, NewCDense will panic. NewCDense will panic if either r or c is zero.
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.
func (*CDense) At ¶
func (m *CDense) At(i, j int) complex128
At returns the element at row i, column j.
func (*CDense) Conj ¶
Conj calculates the element-wise conjugate of a and stores the result in the receiver. Conj will panic if m and a do not have the same dimension unless m is empty.
func (*CDense) Copy ¶
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 VecDense, with a non-unitary increment, Copy will panic.
See the Copier interface for more information.
func (*CDense) Grow ¶
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.
func (*CDense) H ¶
H performs an implicit conjugate transpose by returning the receiver inside a ConjTranspose.
func (*CDense) IsEmpty ¶
IsEmpty returns whether the receiver is empty. Empty matrices can be the receiver for size-restricted operations. The receiver can be zeroed using Reset.
func (*CDense) RawCMatrix ¶
RawCMatrix returns the underlying cblas128.General used by the receiver. Changes to elements in the receiver following the call will be reflected in returned cblas128.General.
func (*CDense) Reset ¶
func (m *CDense) Reset()
Reset zeros the dimensions of the matrix so that it can be reused as the receiver of a dimensionally restricted operation.
Reset should not be used when the matrix shares backing data. See the Reseter interface for more information.
func (*CDense) ReuseAs ¶
ReuseAs changes the receiver if it IsEmpty() to be of size r×c.
ReuseAs re-uses the backing data slice if it has sufficient capacity, otherwise a new slice is allocated. The backing data is zero on return.
ReuseAs panics if the receiver is not empty, and panics if the input sizes are less than one. To empty the receiver for re-use, Reset should be used.
func (*CDense) Set ¶
func (m *CDense) Set(i, j int, v complex128)
Set sets the element at row i, column j to the value v.
func (*CDense) SetRawCMatrix ¶
SetRawCMatrix sets the underlying cblas128.General used by the receiver. Changes to elements in the receiver following the call will be reflected in b.
func (*CDense) Slice ¶
Slice returns a new CMatrix that shares backing data with the receiver. The returned matrix starts at {i,j} of the receiver 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 capacity of the receiver.
type CMatrix ¶
type CMatrix interface { // Dims returns the dimensions of a CMatrix. 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) complex128 // H returns the conjugate transpose of the CMatrix. Whether H // returns a copy of the underlying data is implementation dependent. // This method may be implemented using the ConjTranspose type, which // provides an implicit matrix conjugate transpose. H() CMatrix // T returns the transpose of the CMatrix. Whether T returns a copy of the // underlying data is implementation dependent. // This method may be implemented using the CTranspose type, which // provides an implicit matrix transpose. T() CMatrix }
CMatrix is the basic matrix interface type for complex matrices.
type CTranspose ¶
type CTranspose struct {
CMatrix CMatrix
}
CTranspose is a type for performing an implicit matrix conjugate transpose. It implements the CMatrix interface, returning values from the conjugate transpose of the matrix within.
func (CTranspose) At ¶
func (t CTranspose) At(i, j int) complex128
At returns the value of the element at row i and column j of the conjugate transposed matrix, that is, row j and column i of the CMatrix field.
func (CTranspose) Dims ¶
func (t CTranspose) Dims() (r, c int)
Dims returns the dimensions of the transposed matrix. The number of rows returned is the number of columns in the CMatrix field, and the number of columns is the number of rows in the CMatrix field.
func (CTranspose) H ¶
func (t CTranspose) H() CMatrix
H performs an implicit transpose by returning the receiver inside a ConjTranspose.
func (CTranspose) T ¶
func (t CTranspose) T() CMatrix
T performs an implicit conjugate transpose by returning the CMatrix field.
func (CTranspose) Untranspose ¶
func (t CTranspose) Untranspose() CMatrix
Untranspose returns the CMatrix field.
type CUntransposer ¶
type CUntransposer interface { // Untranspose returns the underlying CMatrix stored for the implicit // transpose. Untranspose() CMatrix }
CUntransposer is a type that can undo an implicit transpose.
type Cholesky ¶
type Cholesky struct {
// contains filtered or unexported fields
}
Cholesky is a symmetric positive definite matrix represented by its Cholesky decomposition.
The decomposition can be constructed using the Factorize method. The factorization itself can be extracted using the UTo or LTo methods, and the original symmetric matrix can be recovered with ToSym.
Note that this matrix representation is useful for certain operations, in particular finding solutions to linear equations. It is very inefficient at other operations, in particular At is slow.
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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // Construct a symmetric positive definite matrix. tmp := mat.NewDense(4, 4, []float64{ 2, 6, 8, -4, 1, 8, 7, -2, 2, 2, 1, 7, 8, -2, -2, 1, }) var a mat.SymDense a.SymOuterK(1, tmp) fmt.Printf("a = %0.4v\n", mat.Formatted(&a, mat.Prefix(" "))) // Compute the cholesky factorization. var chol mat.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 := mat.NewVecDense(4, []float64{1, 2, 3, 4}) var x mat.VecDense if err := chol.SolveVecTo(&x, b); err != nil { fmt.Println("Matrix is near singular: ", err) } fmt.Println("Solve a * x = b") fmt.Printf("x = %0.4v\n", mat.Formatted(&x, mat.Prefix(" "))) // Extract the factorization and check that it equals the original matrix. var t mat.TriDense chol.LTo(&t) var test mat.Dense test.Mul(&t, t.T()) fmt.Println() fmt.Printf("L * Lᵀ = %0.4v\n", mat.Formatted(&a, mat.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ᵀ = ⎡120 114 -4 -16⎤ ⎢114 118 11 -24⎥ ⎢ -4 11 58 17⎥ ⎣-16 -24 17 73⎦
func (*Cholesky) Clone ¶
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.
func (*Cholesky) ExtendVecSym ¶
ExtendVecSym computes the Cholesky decomposition of the original matrix A, whose Cholesky decomposition is in a, extended by a the n×1 vector v according to
[A w] [w' k]
where k = v[n-1] and w = v[:n-1]. The result is stored into the receiver. In order for the updated matrix to be positive definite, it must be the case that k > w' A^-1 w. If this condition does not hold then ExtendVecSym will return false and the receiver will not be updated.
ExtendVecSym will panic if v.Len() != a.Symmetric()+1 or if a does not contain a valid decomposition.
func (*Cholesky) Factorize ¶
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.
func (*Cholesky) InverseTo ¶
InverseTo computes the inverse of the matrix represented by its Cholesky factorization and stores the result into s. 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.
func (*Cholesky) IsEmpty ¶
IsEmpty returns whether the receiver is empty. Empty matrices can be the receiver for size-restricted operations. The receiver can be emptied using Reset.
func (*Cholesky) LTo ¶
LTo stores into dst the n×n lower triangular matrix L from a Cholesky decomposition
A = L * Lᵀ.
If dst is empty, it is resized to be an n×n lower triangular matrix. When dst is non-empty, LTo panics if dst is not n×n or not Lower. LTo will also panic if the receiver does not contain a successful factorization.
func (*Cholesky) LogDet ¶
LogDet returns the log of the determinant of the matrix that has been factorized.
func (*Cholesky) RawU ¶
func (c *Cholesky) RawU() Triangular
RawU returns the Triangular matrix used to store the Cholesky decomposition of the original matrix A. The returned matrix should not be modified. If it is modified, the decomposition is invalid and should not be used.
func (*Cholesky) Reset ¶
func (c *Cholesky) Reset()
Reset resets the factorization so that it can be reused as the receiver of a dimensionally restricted operation.
func (*Cholesky) Scale ¶
Scale multiplies the original matrix A by a positive constant using its Cholesky decomposition, storing the result in-place into the receiver. That is, if the original Cholesky factorization is
Uᵀ * U = A
the updated factorization is
U'ᵀ * U' = f A = A'
Scale panics if the constant is non-positive, or if the receiver is non-empty and is of a different size from the input.
func (*Cholesky) SetFromU ¶
func (c *Cholesky) SetFromU(t Triangular)
SetFromU sets the Cholesky decomposition from the given triangular matrix. SetFromU panics if t is not upper triangular. If the receiver is empty it is resized to be n×n, the size of t. If dst is non-empty, SetFromU panics if c is not of size n×n. Note that t is copied into, not stored inside, the receiver.
func (*Cholesky) SolveCholTo ¶
SolveCholTo finds the matrix X that solves A * X = B where A and B are represented by their Cholesky decompositions a and b. The result is stored in-place into dst. If the Cholesky decomposition is singular or near-singular a Condition error is returned. See the documentation for Condition for more information.
func (*Cholesky) SolveTo ¶
SolveTo finds the matrix X that solves A * X = B where A is represented by the Cholesky decomposition. The result is stored in-place into dst. If the Cholesky decomposition is singular or near-singular a Condition error is returned. See the documentation for Condition for more information.
func (*Cholesky) SolveVecTo ¶
SolveVecTo finds the vector x that solves A * x = b where A is represented by the Cholesky decomposition. The result is stored in-place into dst. If the Cholesky decomposition is singular or near-singular a Condition error is returned. See the documentation for Condition for more information.
func (*Cholesky) SymRankOne ¶
SymRankOne performs a rank-1 update of the original matrix A and refactorizes its Cholesky factorization, storing the result into the receiver. That is, if in the original Cholesky factorization
Uᵀ * U = A,
in the updated factorization
U'ᵀ * U' = A + alpha * x * xᵀ = 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. If the update fails the receiver is left unchanged.
SymRankOne updates a Cholesky factorization in O(n²) time. The Cholesky factorization computation from scratch is O(n³).
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { a := mat.NewSymDense(4, []float64{ 1, 1, 1, 1, 0, 2, 3, 4, 0, 0, 6, 10, 0, 0, 0, 20, }) fmt.Printf("A = %0.4v\n", mat.Formatted(a, mat.Prefix(" "))) // Compute the Cholesky factorization. var chol mat.Cholesky if ok := chol.Factorize(a); !ok { fmt.Println("matrix a is not positive definite.") } x := mat.NewVecDense(4, []float64{0, 0, 0, 1}) fmt.Printf("\nx = %0.4v\n", mat.Formatted(x, mat.Prefix(" "))) // Rank-1 update the factorization. chol.SymRankOne(&chol, 1, x) // Rank-1 update the matrix a. a.SymRankOne(a, 1, x) var au mat.SymDense chol.ToSym(&au) // Print the matrix that was updated directly. fmt.Printf("\nA' = %0.4v\n", mat.Formatted(a, mat.Prefix(" "))) // Print the matrix recovered from the factorization. fmt.Printf("\nU'ᵀ * U' = %0.4v\n", mat.Formatted(&au, mat.Prefix(" "))) }
Output: A = ⎡ 1 1 1 1⎤ ⎢ 1 2 3 4⎥ ⎢ 1 3 6 10⎥ ⎣ 1 4 10 20⎦ x = ⎡0⎤ ⎢0⎥ ⎢0⎥ ⎣1⎦ A' = ⎡ 1 1 1 1⎤ ⎢ 1 2 3 4⎥ ⎢ 1 3 6 10⎥ ⎣ 1 4 10 21⎦ U'ᵀ * U' = ⎡ 1 1 1 1⎤ ⎢ 1 2 3 4⎥ ⎢ 1 3 6 10⎥ ⎣ 1 4 10 21⎦
func (*Cholesky) Symmetric ¶
Symmetric implements the Symmetric interface and returns the number of rows in the matrix (this is also the number of columns).
func (*Cholesky) ToSym ¶
ToSym reconstructs the original positive definite matrix from its Cholesky decomposition, storing the result into dst. If dst is empty it is resized to be n×n. If dst is non-empty, ToSym panics if dst is not of size n×n. ToSym will also panic if the receiver does not contain a successful factorization.
func (*Cholesky) UTo ¶
UTo stores into dst the n×n upper triangular matrix U from a Cholesky decomposition
A = Uᵀ * U.
If dst is empty, it is resized to be an n×n upper triangular matrix. When dst is non-empty, UTo panics if dst is not n×n or not Upper. UTo will also panic if the receiver does not contain a successful factorization.
type ClonerFrom ¶
type ClonerFrom interface {
CloneFrom(a Matrix)
}
A ClonerFrom 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.
type ColNonZeroDoer ¶
A ColNonZeroDoer can call a function for each non-zero element of a column of the receiver. The parameters of the function are the element indices and its value.
type ColViewer ¶
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.
type Condition ¶
type Condition float64
Condition is the condition number of a matrix. The condition number is defined as |A| * |A^-1|.
One important use of Condition is during linear solve routines (finding x such that A * x = b). The condition number of A indicates the accuracy of the computed solution. A Condition error will be returned if the condition number of A is sufficiently large. If A is exactly singular to working precision, Condition == ∞, and the solve algorithm may have completed early. If Condition is large and finite the solve algorithm will be performed, but the computed solution may be inaccurate. Due to the nature of finite precision arithmetic, the value of Condition is only an approximate test of singularity.
type ConjTranspose ¶
type ConjTranspose struct {
CMatrix CMatrix
}
ConjTranspose is a type for performing an implicit matrix conjugate transpose. It implements the CMatrix interface, returning values from the conjugate transpose of the matrix within.
func (ConjTranspose) At ¶
func (t ConjTranspose) At(i, j int) complex128
At returns the value of the element at row i and column j of the conjugate transposed matrix, that is, row j and column i of the CMatrix field.
func (ConjTranspose) Dims ¶
func (t ConjTranspose) Dims() (r, c int)
Dims returns the dimensions of the transposed matrix. The number of rows returned is the number of columns in the CMatrix field, and the number of columns is the number of rows in the CMatrix field.
func (ConjTranspose) H ¶
func (t ConjTranspose) H() CMatrix
H performs an implicit conjugate transpose by returning the CMatrix field.
func (ConjTranspose) T ¶
func (t ConjTranspose) T() CMatrix
T performs an implicit transpose by returning the receiver inside a CTranspose.
func (ConjTranspose) UnConjTranspose ¶
func (t ConjTranspose) UnConjTranspose() CMatrix
UnConjTranspose returns the CMatrix field.
type Copier ¶
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 ¶
type Dense struct {
// contains filtered or unexported fields
}
Dense is a dense matrix representation.
func DenseCopyOf ¶
DenseCopyOf returns a newly allocated copy of the elements of a.
func NewDense ¶
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. NewDense will panic if either r or c is zero.
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.
func (*Dense) Add ¶
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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // Initialize two matrices, a and b. a := mat.NewDense(2, 2, []float64{ 1, 0, 1, 0, }) b := mat.NewDense(2, 2, []float64{ 0, 1, 0, 1, }) // Add a and b, placing the result into c. // Notice that the size is automatically adjusted // when the receiver is empty (has zero size). var c mat.Dense c.Add(a, b) // Print the result using the formatter. fc := mat.Formatted(&c, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("c = %v", fc) }
Output: c = ⎡1 1⎤ ⎣1 1⎦
func (*Dense) Apply ¶
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.
func (*Dense) Augment ¶
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.
func (*Dense) CloneFrom ¶
CloneFrom makes a copy of a into the receiver, overwriting the previous value of the receiver. The clone from operation does not make any restriction on shape and will not cause shadowing.
See the ClonerFrom interface for more information.
func (*Dense) ColView ¶
ColView returns a Vector reflecting the column j, backed by the matrix data.
See ColViewer for more information.
func (*Dense) Copy ¶
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 VecDense, with a non-unitary increment, Copy will panic.
See the Copier interface for more information.
func (*Dense) DivElem ¶
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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // Initialize two matrices, a and b. a := mat.NewDense(2, 2, []float64{ 5, 10, 15, 20, }) b := mat.NewDense(2, 2, []float64{ 5, 5, 5, 5, }) // Divide the elements of a by b, placing the result into a. a.DivElem(a, b) // Print the result using the formatter. fa := mat.Formatted(a, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("a = %v", fa) }
Output: a = ⎡1 2⎤ ⎣3 4⎦
func (*Dense) Exp ¶
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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // Initialize a matrix a with some data. a := mat.NewDense(2, 2, []float64{ 1, 0, 0, 1, }) // Take the exponential of the matrix and place the result in m. var m mat.Dense m.Exp(a) // Print the result using the formatter. fm := mat.Formatted(&m, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("m = %4.2f", fm) }
Output: m = ⎡2.72 0.00⎤ ⎣0.00 2.72⎦
func (*Dense) Grow ¶
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.
func (*Dense) Inverse ¶
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.
Example ¶
package main import ( "fmt" "log" "gonum.org/v1/gonum/mat" ) func main() { // Initialize a matrix A. a := mat.NewDense(2, 2, []float64{ 2, 1, 6, 4, }) // Compute the inverse of A. var aInv mat.Dense err := aInv.Inverse(a) if err != nil { log.Fatalf("A is not invertible: %v", err) } // Print the result using the formatter. fa := mat.Formatted(&aInv, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("aInv = %.2g\n\n", fa) // Confirm that A * A^-1 = I. var I mat.Dense I.Mul(a, &aInv) fi := mat.Formatted(&I, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("I = %v\n\n", fi) // The Inverse operation, however, should typically be avoided. If the // goal is to solve a linear system // A * X = B, // then the inverse is not needed and computing the solution as // X = A^{-1} * B is slower and has worse stability properties than // solving the original problem. In this case, the SolveVec method of // VecDense (if B is a vector) or Solve method of Dense (if B is a // matrix) should be used instead of computing the Inverse of A. b := mat.NewDense(2, 2, []float64{ 2, 3, 1, 2, }) var x mat.Dense err = x.Solve(a, b) if err != nil { log.Fatalf("no solution: %v", err) } // Print the result using the formatter. fx := mat.Formatted(&x, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("x = %.1f", fx) }
Output: aInv = ⎡ 2 -0.5⎤ ⎣-3 1⎦ I = ⎡1 0⎤ ⎣0 1⎦ x = ⎡ 3.5 5.0⎤ ⎣-5.0 -7.0⎦
func (*Dense) IsEmpty ¶
IsEmpty returns whether the receiver is empty. Empty matrices can be the receiver for size-restricted operations. The receiver can be emptied using Reset.
func (*Dense) Kronecker ¶
Kronecker calculates the Kronecker product of a and b, placing the result in the receiver.
func (Dense) MarshalBinary ¶
MarshalBinary encodes the receiver into a binary form and returns the result.
Dense is little-endian encoded as follows:
0 - 3 Version = 1 (uint32) 4 'G' (byte) 5 'F' (byte) 6 'A' (byte) 7 0 (byte) 8 - 15 number of rows (int64) 16 - 23 number of columns (int64) 24 - 31 0 (int64) 32 - 39 0 (int64) 40 - .. 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]
func (Dense) MarshalBinaryTo ¶
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.
func (*Dense) Mul ¶
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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // Initialize two matrices, a and b. a := mat.NewDense(2, 2, []float64{ 4, 0, 0, 4, }) b := mat.NewDense(2, 3, []float64{ 4, 0, 0, 0, 0, 4, }) // Take the matrix product of a and b and place the result in c. var c mat.Dense c.Mul(a, b) // Print the result using the formatter. fc := mat.Formatted(&c, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("c = %v", fc) }
Output: c = ⎡16 0 0⎤ ⎣ 0 0 16⎦
func (*Dense) MulElem ¶
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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // Initialize two matrices, a and b. a := mat.NewDense(2, 2, []float64{ 1, 2, 3, 4, }) b := mat.NewDense(2, 2, []float64{ 1, 2, 3, 4, }) // Multiply the elements of a and b, placing the result into a. a.MulElem(a, b) // Print the result using the formatter. fa := mat.Formatted(a, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("a = %v", fa) }
Output: a = ⎡1 4⎤ ⎣9 16⎦
func (*Dense) Outer ¶
Outer calculates the outer product of the vectors x and y, where x and y are treated as column vectors, and stores the result in the receiver.
m = alpha * x * yᵀ
In order to update an existing matrix, see RankOne.
func (*Dense) Permutation ¶
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.
func (*Dense) Pow ¶
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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // Initialize a matrix with some data. a := mat.NewDense(2, 2, []float64{ 4, 4, 4, 4, }) // Take the second power of matrix a and place the result in m. var m mat.Dense m.Pow(a, 2) // Print the result using the formatter. fm := mat.Formatted(&m, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("m = %v\n\n", fm) // Take the zeroth power of matrix a and place the result in n. // We expect an identity matrix of the same size as matrix a. var n mat.Dense n.Pow(a, 0) // Print the result using the formatter. fn := mat.Formatted(&n, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("n = %v", fn) }
Output: m = ⎡32 32⎤ ⎣32 32⎦ n = ⎡1 0⎤ ⎣0 1⎦
func (*Dense) Product ¶
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.
func (*Dense) RankOne ¶
RankOne performs a rank-one update to the matrix a with the vectors x and y, where x and y are treated as column vectors. The result is stored in the receiver. The Outer method can be used instead of RankOne if a is not needed.
m = a + alpha * x * yᵀ
func (*Dense) RawMatrix ¶
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.
func (*Dense) RawRowView ¶
RawRowView returns a slice backed by the same array as backing the receiver.
func (*Dense) Reset ¶
func (m *Dense) Reset()
Reset empties the matrix so that it can be reused as the receiver of a dimensionally restricted operation.
Reset should not be used when the matrix shares backing data. See the Reseter interface for more information.
func (*Dense) ReuseAs ¶
ReuseAs changes the receiver if it IsEmpty() to be of size r×c.
ReuseAs re-uses the backing data slice if it has sufficient capacity, otherwise a new slice is allocated. The backing data is zero on return.
ReuseAs panics if the receiver is not empty, and panics if the input sizes are less than one. To empty the receiver for re-use, Reset should be used.
func (*Dense) RowView ¶
RowView returns row i of the matrix data represented as a column vector, backed by the matrix data.
See RowViewer for more information.
func (*Dense) Scale ¶
Scale multiplies the elements of a by f, placing the result in the receiver.
See the Scaler interface for more information.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // Initialize a matrix with some data. a := mat.NewDense(2, 2, []float64{ 4, 4, 4, 4, }) // Scale the matrix by a factor of 0.25 and place the result in m. var m mat.Dense m.Scale(0.25, a) // Print the result using the formatter. fm := mat.Formatted(&m, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("m = %4.3f", fm) }
Output: m = ⎡1.000 1.000⎤ ⎣1.000 1.000⎦
func (*Dense) SetCol ¶
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.
func (*Dense) SetRawMatrix ¶
SetRawMatrix sets the underlying blas64.General used by the receiver. Changes to elements in the receiver following the call will be reflected in b.
func (*Dense) SetRow ¶
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.
func (*Dense) Slice ¶
Slice returns a new Matrix that shares backing data with the receiver. The returned matrix starts at {i,j} of the receiver 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 capacity of the receiver.
func (*Dense) Solve ¶
Solve solves the linear least squares problem
minimize over x |b - A*x|_2
where A is an m×n matrix A, b is a given m element vector and x is n element solution vector. Solve assumes that A has full rank, that is
rank(A) = min(m,n)
If m >= n, Solve finds the unique least squares solution of an overdetermined system.
If m < n, there is an infinite number of solutions that satisfy b-A*x=0. In this case Solve finds the unique solution of an underdetermined system that minimizes |x|_2.
Several right-hand side vectors b and solution vectors x can be handled in a single call. Vectors b are stored in the columns of the m×k matrix B. Vectors x will be stored in-place into the n×k receiver.
If A does not have full rank, a Condition error is returned. See the documentation for Condition for more information.
func (*Dense) Stack ¶
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.
func (*Dense) Sub ¶
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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // Initialize two matrices, a and b. a := mat.NewDense(2, 2, []float64{ 1, 1, 1, 1, }) b := mat.NewDense(2, 2, []float64{ 1, 0, 0, 1, }) // Subtract b from a, placing the result into a. a.Sub(a, b) // Print the result using the formatter. fa := mat.Formatted(a, mat.Prefix(" "), mat.Squeeze()) fmt.Printf("a = %v", fa) }
Output: a = ⎡0 1⎤ ⎣1 0⎦
func (*Dense) Trace ¶
Trace returns the trace of the matrix. The matrix must be square or Trace will panic.
func (*Dense) UnmarshalBinary ¶
UnmarshalBinary decodes the binary form into the receiver. It panics if the receiver is a non-empty 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.
func (*Dense) UnmarshalBinaryFrom ¶
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-empty 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.
type DiagDense ¶
type DiagDense struct {
// contains filtered or unexported fields
}
DiagDense represents a diagonal matrix in dense storage format.
func NewDiagDense ¶
NewDiagDense creates a new Diagonal matrix with n rows and n columns. The length of data must be n or data must be nil, otherwise NewDiagDense will panic. NewDiagDense will panic if n is zero.
func (*DiagDense) Bandwidth ¶
Bandwidth returns the upper and lower bandwidths of the matrix. These values are always zero for diagonal matrices.
func (*DiagDense) DiagFrom ¶
DiagFrom copies the diagonal of m into the receiver. The receiver must be min(r, c) long or empty, otherwise DiagFrom will panic.
func (*DiagDense) IsEmpty ¶
IsEmpty returns whether the receiver is empty. Empty matrices can be the receiver for size-restricted operations. The receiver can be emptied using Reset.
func (*DiagDense) RawBand ¶
RawBand returns the underlying data used by the receiver represented as a blas64.Band. Changes to elements in the receiver following the call will be reflected in returned blas64.Band.
func (*DiagDense) RawSymBand ¶
func (d *DiagDense) RawSymBand() blas64.SymmetricBand
RawSymBand returns the underlying data used by the receiver represented as a blas64.SymmetricBand. Changes to elements in the receiver following the call will be reflected in returned blas64.Band.
func (*DiagDense) Reset ¶
func (d *DiagDense) Reset()
Reset empties the matrix so that it can be reused as the receiver of a dimensionally restricted operation.
Reset should not be used when the matrix shares backing data. See the Reseter interface for more information.
func (*DiagDense) SetDiag ¶
SetDiag sets the element at row i, column i to the value v. It panics if the location is outside the appropriate region of the matrix.
func (*DiagDense) SymBand ¶
SymBand returns the number of rows/columns in the matrix, and the size of the bandwidth.
func (*DiagDense) TBand ¶
TBand performs an implicit transpose by returning the receiver inside a TransposeBand.
func (*DiagDense) TTri ¶
func (d *DiagDense) TTri() Triangular
TTri returns the transpose of the matrix. Note that Diagonal matrices are Upper by default.
func (*DiagDense) TTriBand ¶
TTriBand performs an implicit transpose by returning the receiver inside a TransposeTriBand. Note that Diagonal matrices are Upper by default.
func (*DiagDense) TriBand ¶
TriBand returns the number of rows/columns in the matrix, the size of the bandwidth, and the orientation. Note that Diagonal matrices are Upper by default.
type Diagonal ¶
type Diagonal interface { Matrix // Diag returns the number of rows/columns in the matrix. Diag() int // Bandwidth and TBand are included in the Diagonal interface // to allow the use of Diagonal types in banded functions. // Bandwidth will always return (0, 0). Bandwidth() (kl, ku int) TBand() Banded // Triangle and TTri are included in the Diagonal interface // to allow the use of Diagonal types in triangular functions. Triangle() (int, TriKind) TTri() Triangular // Symmetric and SymBand are included in the Diagonal interface // to allow the use of Diagonal types in symmetric and banded symmetric // functions respectively. Symmetric() int SymBand() (n, k int) // TriBand and TTriBand are included in the Diagonal interface // to allow the use of Diagonal types in triangular banded functions. TriBand() (n, k int, kind TriKind) TTriBand() TriBanded }
Diagonal represents a diagonal matrix, that is a square matrix that only has non-zero terms on the diagonal.
type Eigen ¶
type Eigen struct {
// contains filtered or unexported fields
}
Eigen is a type for creating and using the eigenvalue decomposition of a dense matrix.
Example ¶
package main import ( "fmt" "log" "gonum.org/v1/gonum/mat" ) func main() { a := mat.NewDense(2, 2, []float64{ 1, -1, 1, 1, }) fmt.Printf("A = %v\n\n", mat.Formatted(a, mat.Prefix(" "))) var eig mat.Eigen ok := eig.Factorize(a, mat.EigenLeft) if !ok { log.Fatal("Eigendecomposition failed") } fmt.Printf("Eigenvalues of A:\n%v\n", eig.Values(nil)) }
Output: A = ⎡ 1 -1⎤ ⎣ 1 1⎦ Eigenvalues of A: [(1+1i) (1-1i)]
func (*Eigen) Factorize ¶
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 eigenvalue.
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, Factorize computes the eigenvalues of the matrix. kind specifies which of the eigenvectors, if any, to compute. See the EigenKind documentation for more information. 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.
func (*Eigen) Kind ¶
Kind returns the EigenKind of the decomposition. If no decomposition has been computed, Kind returns -1.
func (*Eigen) LeftVectorsTo ¶
LeftVectorsTo stores the left eigenvectors of the decomposition into the columns of dst. The computed eigenvectors are normalized to have Euclidean norm equal to 1 and largest component real.
If dst is empty, LeftVectorsTo will resize dst to be n×n. When dst is non-empty, LeftVectorsTo will panic if dst is not n×n. LeftVectorsTo will also panic if the left eigenvectors were not computed during the factorization, or if the receiver does not contain a successful factorization
func (*Eigen) Values ¶
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.
func (*Eigen) VectorsTo ¶
VectorsTo stores the right eigenvectors of the decomposition into the columns of dst. The computed eigenvectors are normalized to have Euclidean norm equal to 1 and largest component real.
If dst is empty, VectorsTo will resize dst to be n×n. When dst is non-empty, VectorsTo will panic if dst is not n×n. VectorsTo will also panic if the eigenvectors were not computed during the factorization, or if the receiver does not contain a successful factorization.
type EigenKind ¶
type EigenKind int
EigenKind specifies the computation of eigenvectors during factorization.
const ( // EigenNone specifies to not compute any eigenvectors. EigenNone EigenKind = 0 // EigenLeft specifies to compute the left eigenvectors. EigenLeft EigenKind = 1 << iota // EigenRight specifies to compute the right eigenvectors. EigenRight // EigenBoth is a convenience value for computing both eigenvectors. EigenBoth EigenKind = EigenLeft | EigenRight )
type EigenSym ¶
type EigenSym struct {
// contains filtered or unexported fields
}
EigenSym is a type for creating and manipulating the Eigen decomposition of symmetric matrices.
Example ¶
package main import ( "fmt" "log" "gonum.org/v1/gonum/mat" ) func main() { a := mat.NewSymDense(2, []float64{ 7, 0.5, 0.5, 1, }) fmt.Printf("A = %v\n\n", mat.Formatted(a, mat.Prefix(" "))) var eigsym mat.EigenSym ok := eigsym.Factorize(a, true) if !ok { log.Fatal("Symmetric eigendecomposition failed") } fmt.Printf("Eigenvalues of A:\n%1.3f\n\n", eigsym.Values(nil)) var ev mat.Dense eigsym.VectorsTo(&ev) fmt.Printf("Eigenvectors of A:\n%1.3f\n\n", mat.Formatted(&ev)) }
Output: A = ⎡ 7 0.5⎤ ⎣0.5 1⎦ Eigenvalues of A: [0.959 7.041] Eigenvectors of A: ⎡ 0.082 -0.997⎤ ⎣-0.997 -0.082⎦
func (*EigenSym) Factorize ¶
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. Factorize computes the eigenvalues in ascending order. 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.
func (*EigenSym) Values ¶
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.
func (*EigenSym) VectorsTo ¶
VectorsTo stores the eigenvectors of the decomposition into the columns of dst.
If dst is empty, VectorsTo will resize dst to be n×n. When dst is non-empty, VectorsTo will panic if dst is not n×n. VectorsTo will also panic if the eigenvectors were not computed during the factorization, or if the receiver does not contain a successful factorization.
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
Error represents matrix handling errors. These errors can be recovered by Maybe wrappers.
type ErrorStack ¶
type ErrorStack struct { Err error // StackTrace is the stack trace // recovered by Maybe, MaybeFloat // or MaybeComplex. StackTrace string }
ErrorStack represents matrix handling errors that have been recovered by Maybe wrappers.
func (ErrorStack) Error ¶
func (err ErrorStack) Error() string
type FormatOption ¶
type FormatOption func(*formatter)
FormatOption is a functional option for matrix formatting.
func DotByte ¶
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 ¶
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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { // Excerpt allows diagnostic display of very large // matrices and vectors. // The big matrix is too large to properly print... big := mat.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", mat.Formatted(big, mat.Prefix(" "), mat.Excerpt(3))) // The long vector is also too large, ... long := mat.NewVecDense(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", mat.Formatted(long, mat.Prefix(" "), mat.Excerpt(3))) // or its transpose. fmt.Printf("excerpt long row vector: %v\n", mat.Formatted(long.T(), mat.Prefix(" "), mat.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 FormatMATLAB ¶
func FormatMATLAB() FormatOption
FormatMATLAB sets the printing behavior to output MATLAB syntax. If MATLAB syntax is specified, the ' ' verb flag and Excerpt option are ignored. If the alternative syntax verb flag, '#' is used the matrix is formatted in rows and columns.
func FormatPython ¶
func FormatPython() FormatOption
FormatPython sets the printing behavior to output Python syntax. If Python syntax is specified, the ' ' verb flag and Excerpt option are ignored. If the alternative syntax verb flag, '#' is used the matrix is formatted in rows and columns.
func Prefix ¶
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 after the first line.
func Squeeze ¶
func Squeeze() FormatOption
Squeeze sets the printing behavior to minimise column width for each individual column.
type GSVD ¶
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.
The factorization is a linear transformation of the data sets from the given variable×sample spaces to reduced and diagonalized "eigenvariable"×"eigensample" spaces.
Example ¶
// Perform a GSVD factorization on food production/consumption data for the // three years 1990, 2000 and 2014, for Africa and Latin America/Caribbean. // // See Lee et al. doi:10.1371/journal.pone.0030098 and // Alter at al. doi:10.1073/pnas.0530258100 for more details. var gsvd mat.GSVD ok := gsvd.Factorize(FAO.Africa, FAO.LatinAmericaCaribbean, mat.GSVDU|mat.GSVDV|mat.GSVDQ) if !ok { log.Fatal("GSVD factorization failed") } var u, v mat.Dense gsvd.UTo(&u) gsvd.VTo(&v) s1 := gsvd.ValuesA(nil) s2 := gsvd.ValuesB(nil) fmt.Printf("Africa\n\ts1 = %.4f\n\n\tU = %.4f\n\n", s1, mat.Formatted(&u, mat.Prefix("\t "), mat.Excerpt(2))) fmt.Printf("Latin America/Caribbean\n\ts2 = %.4f\n\n\tV = %.4f\n", s2, mat.Formatted(&v, mat.Prefix("\t "), mat.Excerpt(2))) var q, zR mat.Dense gsvd.QTo(&q) gsvd.ZeroRTo(&zR) q.Mul(&zR, &q) fmt.Printf("\nCommon basis vectors\n\n\tQᵀ = %.4f\n", mat.Formatted(q.T(), mat.Prefix("\t "))) // Calculate the antisymmetric angular distances for each eigenvariable. fmt.Println("\nSignificance:") for i := 0; i < 3; i++ { fmt.Printf("\teigenvar_%d: %+.4f\n", i, math.Atan(s1[i]/s2[i])-math.Pi/4) }
Output: Africa s1 = [1.0000 0.9344 0.5118] U = Dims(21, 21) ⎡-0.0005 0.0142 ... ... -0.0060 -0.0055⎤ ⎢-0.0010 0.0019 0.0071 0.0075⎥ . . . ⎢-0.0007 -0.0024 0.9999 -0.0001⎥ ⎣-0.0010 -0.0016 ... ... -0.0001 0.9999⎦ Latin America/Caribbean s2 = [0.0047 0.3563 0.8591] V = Dims(14, 14) ⎡ 0.1362 0.0008 ... ... 0.0700 0.2636⎤ ⎢ 0.1830 -0.0040 0.2908 0.7834⎥ . . . ⎢-0.2598 -0.0324 0.9339 -0.2170⎥ ⎣-0.8386 0.1494 ... ... -0.1639 0.4121⎦ Common basis vectors Qᵀ = ⎡ -8172.4084 -4524.2933 4813.9616⎤ ⎢ 22581.8020 12397.1070 -16364.8933⎥ ⎣ -8910.8462 -10902.1488 15762.8719⎦ Significance: eigenvar_0: +0.7807 eigenvar_1: +0.4211 eigenvar_2: -0.2482
func (*GSVD) Factorize ¶
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 == GSVDAll) deconstructs A and B as
A = U * Σ₁ * [ 0 R ] * Qᵀ B = V * Σ₂ * [ 0 R ] * Qᵀ
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ᵀ Bᵀ ]ᵀ.
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.
func (*GSVD) GeneralizedValues ¶
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.
func (*GSVD) Kind ¶
Kind returns the GSVDKind of the decomposition. If no decomposition has been computed, Kind returns -1.
func (*GSVD) QTo ¶
QTo extracts the matrix Q from the singular value decomposition, storing the result into dst. Q is size c×c.
If dst is empty, QTo will resize dst to be c×c. When dst is non-empty, QTo will panic if dst is not c×c. QTo will also panic if the receiver does not contain a successful factorization.
func (*GSVD) SigmaATo ¶
SigmaATo extracts the matrix Σ₁ from the singular value decomposition, storing the result into dst. Σ₁ is size r×(k+l).
If dst is empty, SigmaATo will resize dst to be r×(k+l). When dst is non-empty, SigmATo will panic if dst is not r×(k+l). SigmaATo will also panic if the receiver does not contain a successful factorization.
func (*GSVD) SigmaBTo ¶
SigmaBTo extracts the matrix Σ₂ from the singular value decomposition, storing the result into dst. Σ₂ is size p×(k+l).
If dst is empty, SigmaBTo will resize dst to be p×(k+l). When dst is non-empty, SigmBTo will panic if dst is not p×(k+l). SigmaBTo will also panic if the receiver does not contain a successful factorization.
func (*GSVD) UTo ¶
UTo extracts the matrix U from the singular value decomposition, storing the result into dst. U is size r×r.
If dst is empty, UTo will resize dst to be r×r. When dst is non-empty, UTo will panic if dst is not r×r. UTo will also panic if the receiver does not contain a successful factorization.
func (*GSVD) VTo ¶
VTo extracts the matrix V from the singular value decomposition, storing the result into dst. V is size p×p.
If dst is empty, VTo will resize dst to be p×p. When dst is non-empty, VTo will panic if dst is not p×p. VTo will also panic if the receiver does not contain a successful factorization.
func (*GSVD) ValuesA ¶
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.
func (*GSVD) ValuesB ¶
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.
func (*GSVD) ZeroRTo ¶
ZeroRTo extracts the matrix [ 0 R ] from the singular value decomposition, storing the result into dst. [ 0 R ] is of size (k+l)×c.
If dst is empty, ZeroRTo will resize dst to be (k+l)×c. When dst is non-empty, ZeroRTo will panic if dst is not (k+l)×c. ZeroRTo will also panic if the receiver does not contain a successful factorization.
type GSVDKind ¶
type GSVDKind int
GSVDKind specifies the treatment of singular vectors during a GSVD factorization.
const ( // GSVDNone specifies that no singular vectors should be computed during // the decomposition. GSVDNone GSVDKind = 0 // GSVDU specifies that the U singular vectors should be computed during // the decomposition. GSVDU GSVDKind = 1 << iota // GSVDV specifies that the V singular vectors should be computed during // the decomposition. GSVDV // GSVDQ specifies that the Q singular vectors should be computed during // the decomposition. GSVDQ // GSVDAll is a convenience value for computing all of the singular vectors. GSVDAll = GSVDU | GSVDV | GSVDQ )
type Grower ¶
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 ¶
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.
The factorization is a linear transformation of the data sets from the given variable×sample spaces to reduced and diagonalized "eigenvariable"×"eigensample" spaces.
Example ¶
// Perform an HOGSVD factorization on food production/consumption data for the // three years 1990, 2000 and 2014. // // See Ponnapalli et al. doi:10.1371/journal.pone.0028072 and // Alter at al. doi:10.1073/pnas.0530258100 for more details. var gsvd mat.HOGSVD ok := gsvd.Factorize(FAO.Africa, FAO.Asia, FAO.LatinAmericaCaribbean, FAO.Oceania) if !ok { log.Fatalf("HOGSVD factorization failed: %v", gsvd.Err()) } for i, n := range []string{"Africa", "Asia", "Latin America/Caribbean", "Oceania"} { var u mat.Dense gsvd.UTo(&u, i) s := gsvd.Values(nil, i) fmt.Printf("%s\n\ts_%d = %.4f\n\n\tU_%[2]d = %.4[4]f\n", n, i, s, mat.Formatted(&u, mat.Prefix("\t "))) } var v mat.Dense gsvd.VTo(&v) fmt.Printf("\nCommon basis vectors\n\n\tVᵀ = %.4f", mat.Formatted(v.T(), mat.Prefix("\t ")))
Output: Africa s_0 = [45507.3278 18541.9293 21503.0778] U_0 = ⎡-0.0005 -0.0039 -0.0019⎤ ⎢-0.0010 -0.0007 -0.0012⎥ ⎢-1.0000 -0.0507 -0.9964⎥ ⎢-0.0022 -0.2906 -0.0415⎥ ⎢ 0.0001 -0.0127 -0.0016⎥ ⎢ 0.0003 -0.0067 -0.0010⎥ ⎢ 0.0003 -0.0022 -0.0003⎥ ⎢-0.0086 -0.9550 0.0734⎥ ⎢ 0.0017 0.0002 0.0059⎥ ⎢-0.0002 -0.0088 -0.0014⎥ ⎢-0.0006 -0.0078 -0.0001⎥ ⎢-0.0005 -0.0076 0.0003⎥ ⎢ 0.0001 -0.0090 0.0008⎥ ⎢-0.0005 -0.0050 0.0029⎥ ⎢-0.0011 -0.0078 -0.0012⎥ ⎢-0.0014 -0.0058 -0.0002⎥ ⎢ 0.0007 -0.0095 0.0020⎥ ⎢-0.0008 -0.0081 -0.0009⎥ ⎢ 0.0004 -0.0092 0.0006⎥ ⎢-0.0007 -0.0079 -0.0006⎥ ⎣-0.0011 -0.0076 -0.0010⎦ Asia s_1 = [77228.2804 8413.7024 14711.1879] U_1 = ⎡ 0.0005 -0.0080 0.0011⎤ ⎢ 0.0008 -0.0108 0.0016⎥ ⎢-0.9998 0.0612 0.9949⎥ ⎢ 0.0007 -0.5734 -0.0468⎥ ⎢ 0.0001 -0.0265 -0.0022⎥ ⎢ 0.0001 -0.0165 -0.0019⎥ ⎢ 0.0000 -0.0070 -0.0013⎥ ⎢ 0.0196 -0.8148 0.0893⎥ ⎢ 0.0002 -0.0063 0.0012⎥ ⎢-0.0001 -0.0135 -0.0013⎥ ⎢-0.0004 -0.0135 0.0019⎥ ⎢-0.0005 -0.0132 0.0014⎥ ⎢ 0.0003 -0.0155 0.0045⎥ ⎢-0.0003 -0.0130 0.0025⎥ ⎢-0.0007 -0.0105 0.0016⎥ ⎢-0.0006 -0.0129 0.0007⎥ ⎢-0.0006 -0.0178 -0.0023⎥ ⎢-0.0003 -0.0149 0.0016⎥ ⎢-0.0001 -0.0134 0.0030⎥ ⎢-0.0004 -0.0154 0.0010⎥ ⎣-0.0009 -0.0147 -0.0019⎦ Latin America/Caribbean s_2 = [274.1364 20736.3116 729.6947] U_2 = ⎡ 0.1060 -0.0021 0.0174⎤ ⎢ 0.1415 -0.0016 0.0289⎥ ⎢ 0.2350 -0.2669 -0.9212⎥ ⎢ 0.0290 -0.0118 -0.0429⎥ ⎢ 0.0226 -0.0043 -0.0213⎥ ⎢ 0.0117 -0.0016 -0.0197⎥ ⎢-0.6263 -0.9635 0.2234⎥ ⎢ 0.2334 -0.0013 0.1275⎥ ⎢-0.0358 -0.0085 -0.0498⎥ ⎢-0.1238 -0.0054 0.0313⎥ ⎢-0.0421 -0.0059 0.0528⎥ ⎢-0.1471 -0.0056 0.0350⎥ ⎢-0.2158 -0.0052 -0.0044⎥ ⎣-0.6154 -0.0078 -0.2717⎦ Oceania s_3 = [8954.1914 6942.6316 17233.0561] U_3 = ⎡-0.0080 -0.0012 -0.0040⎤ ⎢ 0.0004 -0.0014 0.0001⎥ ⎢ 0.9973 -0.0315 0.9991⎥ ⎢ 0.0473 -0.7426 -0.0359⎥ ⎢ 0.0018 -0.0342 -0.0020⎥ ⎢-0.0005 -0.0148 -0.0016⎥ ⎢-0.0004 -0.0047 -0.0007⎥ ⎢-0.0246 -0.6642 -0.0138⎥ ⎢ 0.0003 -0.0287 -0.0023⎥ ⎢-0.0011 -0.0148 -0.0014⎥ ⎢-0.0108 -0.0198 -0.0039⎥ ⎢-0.0149 -0.0183 -0.0048⎥ ⎢-0.0178 -0.0208 -0.0075⎥ ⎢-0.0266 -0.0063 -0.0016⎥ ⎢-0.0012 -0.0234 -0.0006⎥ ⎢-0.0084 -0.0184 -0.0030⎥ ⎢-0.0232 -0.0191 -0.0124⎥ ⎢-0.0072 -0.0226 -0.0035⎥ ⎢-0.0150 -0.0144 -0.0045⎥ ⎢-0.0068 -0.0227 -0.0034⎥ ⎣-0.0127 -0.0136 -0.0049⎦ Common basis vectors Vᵀ = ⎡-0.0897 -0.4460 -0.8905⎤ ⎢-0.4911 -0.5432 -0.6810⎥ ⎣ 0.0644 0.2841 0.9566⎦
func (*HOGSVD) Factorize ¶
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ᵀ M_1 = U_1 * Σ_1 * Vᵀ . . . M_{n-1} = U_{n-1} * Σ_{n-1} * Vᵀ
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.
func (*HOGSVD) Len ¶
Len returns the number of matrices that have been factorized. If Len returns zero, the factorization was not successful.
func (*HOGSVD) UTo ¶
UTo extracts the matrix U_n from the singular value decomposition, storing the result in-place into dst. U_n is size r×c.
If dst is empty, UTo will resize dst to be r×c. When dst is non-empty, UTo will panic if dst is not r×c. UTo will also panic if the receiver does not contain a successful factorization.
func (*HOGSVD) VTo ¶
VTo extracts the matrix V from the singular value decomposition, storing the result in-place into dst. V is size c×c.
If dst is empty, VTo will resize dst to be c×c. When dst is non-empty, VTo will panic if dst is not c×c. VTo will also panic if the receiver does not contain a successful factorization.
func (*HOGSVD) Values ¶
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 ¶
type LQ struct {
// contains filtered or unexported fields
}
LQ is a type for creating and using the LQ factorization of a matrix.
func (*LQ) Cond ¶
Cond returns the condition number for the factorized matrix. Cond will panic if the receiver does not contain a factorization.
func (*LQ) Factorize ¶
Factorize computes the LQ factorization of an m×n matrix a where m <= n. 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 lower triangular matrix. L and Q can be extracted using the LTo and QTo methods.
func (*LQ) LTo ¶
LTo extracts the m×n lower trapezoidal matrix from a LQ decomposition.
If dst is empty, LTo will resize dst to be r×c. When dst is non-empty, LTo will panic if dst is not r×c. LTo will also panic if the receiver does not contain a successful factorization.
func (*LQ) QTo ¶
QTo extracts the n×n orthonormal matrix Q from an LQ decomposition.
If dst is empty, QTo will resize dst to be c×c. When dst is non-empty, QTo will panic if dst is not c×c. QTo will also panic if the receiver does not contain a successful factorization.
func (*LQ) SolveTo ¶
SolveTo 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. 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 dst. SolveTo will panic if the receiver does not contain a factorization.
type LU ¶
type LU struct {
// contains filtered or unexported fields
}
LU is a type for creating and using the LU factorization of a matrix.
func (*LU) Cond ¶
Cond returns the condition number for the factorized matrix. Cond will panic if the receiver does not contain a factorization.
func (*LU) Det ¶
Det returns the determinant of the matrix that has been factorized. In many expressions, using LogDet will be more numerically stable. Det will panic if the receiver does not contain a factorization.
func (*LU) Factorize ¶
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 LU.LTo and LU.UTo methods.
func (*LU) LTo ¶
LTo extracts the lower triangular matrix from an LU factorization.
If dst is empty, LTo will resize dst to be a lower-triangular n×n matrix. When dst is non-empty, LTo will panic if dst is not n×n or not Lower. LTo will also panic if the receiver does not contain a successful factorization.
func (*LU) LogDet ¶
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. LogDet will panic if the receiver does not contain a factorization.
func (*LU) Pivot ¶
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. Pivot will panic if the receiver does not contain a factorization.
func (*LU) RankOne ¶
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ᵀ. RankOne will panic if orig does not contain a factorization.
func (*LU) Reset ¶
func (lu *LU) Reset()
Reset resets the factorization so that it can be reused as the receiver of a dimensionally restricted operation.
func (*LU) SolveTo ¶
SolveTo solves a system of linear equations using the LU decomposition of a matrix. It computes
A * X = B if trans == false Aᵀ * X = B if trans == true
In both cases, A is represented in LU factorized form, and the matrix X is stored into dst.
If A is singular or near-singular a Condition error is returned. See the documentation for Condition for more information. SolveTo will panic if the receiver does not contain a factorization.
func (*LU) SolveVecTo ¶
SolveVecTo solves a system of linear equations using the LU decomposition of a matrix. It computes
A * x = b if trans == false Aᵀ * x = b if trans == true
In both cases, A is represented in LU factorized form, and the vector x is stored into dst.
If A is singular or near-singular a Condition error is returned. See the documentation for Condition for more information. SolveVecTo will panic if the receiver does not contain a factorization.
func (*LU) UTo ¶
UTo extracts the upper triangular matrix from an LU factorization.
If dst is empty, UTo will resize dst to be an upper-triangular n×n matrix. When dst is non-empty, UTo will panic if dst is not n×n or not Upper. UTo will also panic if the receiver does not contain a successful factorization.
type Matrix ¶
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 ¶
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 MutableBanded ¶
A MutableBanded can set elements of a band matrix.
type MutableDiagonal ¶
MutableDiagonal is a Diagonal matrix whose elements can be set.
type MutableSymBanded ¶
MutableSymBanded is a symmetric band matrix interface type that allows elements to be altered.
type MutableSymmetric ¶
A MutableSymmetric can set elements of a symmetric matrix.
type MutableTriBanded ¶
MutableTriBanded is a triangular band matrix interface type that allows elements to be altered.
type MutableTriangular ¶
type MutableTriangular interface { Triangular SetTri(i, j int, v float64) }
A MutableTriangular can set elements of a triangular matrix.
type MutableVector ¶
A MutableVector can set elements of a vector.
type NonZeroDoer ¶
A NonZeroDoer can call a function for each non-zero element of the receiver. The parameters of the function are the element indices and its value.
type QR ¶
type QR struct {
// contains filtered or unexported fields
}
QR is a type for creating and using the QR factorization of a matrix.
func (*QR) Cond ¶
Cond returns the condition number for the factorized matrix. Cond will panic if the receiver does not contain a factorization.
func (*QR) Factorize ¶
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 using the QTo and RTo methods.
func (*QR) QTo ¶
QTo extracts the r×r orthonormal matrix Q from a QR decomposition.
If dst is empty, QTo will resize dst to be r×r. When dst is non-empty, QTo will panic if dst is not r×r. QTo will also panic if the receiver does not contain a successful factorization.
func (*QR) RTo ¶
RTo extracts the m×n upper trapezoidal matrix from a QR decomposition.
If dst is empty, RTo will resize dst to be r×c. When dst is non-empty, RTo will panic if dst is not r×c. RTo will also panic if the receiver does not contain a successful factorization.
func (*QR) SolveTo ¶
SolveTo 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. 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ᵀ * X = B.
The solution matrix, X, is stored in place into dst. SolveTo will panic if the receiver does not contain a factorization.
type RawBander ¶
A RawBander can return a blas64.Band representation of the receiver. Changes to the blas64.Band.Data slice will be reflected in the original matrix, changes to the Rows, Cols, KL, KU and Stride fields will not.
type RawCMatrixer ¶
A RawCMatrixer can return a cblas128.General representation of the receiver. Changes to the cblas128.General.Data slice will be reflected in the original matrix, changes to the Rows, Cols and Stride fields will not.
type RawColViewer ¶
A RawColViewer can return a slice of float64 reflecting a column that is backed by the matrix data.
type RawMatrixSetter ¶
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.
type RawMatrixer ¶
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.
type RawRowViewer ¶
A RawRowViewer can return a slice of float64 reflecting a row that is backed by the matrix data.
type RawSymBander ¶
type RawSymBander interface {
RawSymBand() blas64.SymmetricBand
}
A RawSymBander can return a blas64.SymmetricBand representation of the receiver. Changes to the blas64.SymmetricBand.Data slice will be reflected in the original matrix, changes to the N, K, Stride and Uplo fields will not.
type RawSymmetricer ¶
A RawSymmetricer can return a view of itself as a BLAS Symmetric matrix.
type RawTriBander ¶
type RawTriBander interface {
RawTriBand() blas64.TriangularBand
}
A RawTriBander can return a blas64.TriangularBand representation of the receiver. Changes to the blas64.TriangularBand.Data slice will be reflected in the original matrix, changes to the N, K, Stride, Uplo and Diag fields will not.
type RawTriangular ¶
type RawTriangular interface {
RawTriangular() blas64.Triangular
}
A RawTriangular can return a blas64.Triangular representation of the receiver. Changes to the blas64.Triangular.Data slice will be reflected in the original matrix, changes to the N, Stride, Uplo and Diag fields will not.
type RawVectorer ¶
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 ¶
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 Reset may result in data corruption in elements outside the view. Similarly, if the matrix shares backing data with another variable, using Reset may lead to unexpected changes in data values.
type RowNonZeroDoer ¶
A RowNonZeroDoer can call a function for each non-zero element of a row of the receiver. The parameters of the function are the element indices and its value.
type RowViewer ¶
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 ¶
type SVD struct {
// contains filtered or unexported fields
}
SVD is a type for creating and using the Singular Value Decomposition of a matrix.
func (*SVD) Cond ¶
Cond returns the 2-norm condition number for the factorized matrix. Cond will panic if the receiver does not contain a successful factorization.
func (*SVD) Factorize ¶
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) is a factorization of an m×n matrix A of the form
A = U * Σ * Vᵀ
where Σ is an m×n diagonal matrix, U is an m×m orthogonal matrix, and V is an n×n orthogonal matrix. The diagonal elements of Σ are the singular values of A. The first min(m,n) columns of U and V are, respectively, the left and right singular vectors of A.
Significant storage space can be saved by using the thin representation of the SVD (kind == SVDThin) instead of the full SVD, especially if m >> n or m << n. The thin SVD finds
A = U~ * Σ * V~ᵀ
where U~ is of size m×min(m,n), Σ is a diagonal matrix of size min(m,n)×min(m,n) and V~ is of size n×min(m,n).
Factorize returns whether the decomposition succeeded. If the decomposition failed, routines that require a successful factorization will panic.
func (*SVD) Kind ¶
Kind returns the SVDKind of the decomposition. If no decomposition has been computed, Kind returns -1.
func (*SVD) Rank ¶
Rank returns the rank of A based on the count of singular values greater than rcond scaled by the largest singular value. Rank will panic if the receiver does not contain a successful factorization or rcond is negative.
func (*SVD) SolveTo ¶
SolveTo calculates the minimum-norm solution to a linear least squares problem
minimize over n-element vectors x: |b - A*x|_2 and |x|_2
where b is a given m-element vector, using the SVD of m×n matrix A stored in the receiver. A may be rank-deficient, that is, the given effective rank can be
rank ≤ min(m,n)
The rank can be computed using SVD.Rank.
Several right-hand side vectors b and solution vectors x can be handled in a single call. Vectors b are stored in the columns of the m×k matrix B and the resulting vectors x will be stored in the columns of dst. dst must be either empty or have the size equal to n×k.
The decomposition must have been factorized computing both the U and V singular vectors.
SolveTo returns the residuals calculated from the complete SVD. For this value to be valid the factorization must have been performed with at least SVDFullU.
Example ¶
package main import ( "fmt" "log" "gonum.org/v1/gonum/mat" ) func main() { // The system described by A is rank deficient. a := mat.NewDense(5, 3, []float64{ -1.7854591879711257, -0.42687285925779594, -0.12730256811265162, -0.5728984211439724, -0.10093393134001777, -0.1181901192353067, 1.2484316018707418, 0.5646683943038734, -0.48229492403243485, 0.10174927665169475, -0.5805410929482445, 1.3054473231942054, -1.134174808195733, -0.4732430202414438, 0.3528489486370508, }) // Perform an SVD retaining all singular vectors. var svd mat.SVD ok := svd.Factorize(a, mat.SVDFull) if !ok { log.Fatal("failed to factorize A") } // Determine the rank of the A matrix with a near zero condition threshold. const rcond = 1e-15 rank := svd.Rank(rcond) if rank == 0 { log.Fatal("zero rank system") } b := mat.NewDense(5, 2, []float64{ -2.318, -4.35, -0.715, 1.451, 1.836, -0.119, -0.357, 3.094, -1.636, 0.021, }) // Find a least-squares solution using the determined parts of the system. var x mat.Dense svd.SolveTo(&x, b, rank) fmt.Printf("singular values = %v\nrank = %d\nx = %.15f", format(svd.Values(nil), 4, rcond), rank, mat.Formatted(&x, mat.Prefix(" "))) } func format(vals []float64, prec int, eps float64) []string { s := make([]string, len(vals)) for i, v := range vals { if v < eps { s[i] = fmt.Sprintf("<%.*g", prec, eps) continue } s[i] = fmt.Sprintf("%.*g", prec, v) } return s }
Output: singular values = [2.685 1.526 <1e-15] rank = 2 x = ⎡ 1.212064313552347 1.507467451093930⎤ ⎢ 0.415400738264774 -0.624498607705372⎥ ⎣-0.183184442255280 2.221334193689124⎦
func (*SVD) SolveVecTo ¶
SolveVecTo calculates the minimum-norm solution to a linear least squares problem
minimize over n-element vectors x: |b - A*x|_2 and |x|_2
where b is a given m-element vector, using the SVD of m×n matrix A stored in the receiver. A may be rank-deficient, that is, the given effective rank can be
rank ≤ min(m,n)
The rank can be computed using SVD.Rank.
The resulting vector x will be stored in dst. dst must be either empty or have length equal to n.
The decomposition must have been factorized computing both the U and V singular vectors.
SolveVecTo returns the residuals calculated from the complete SVD. For this value to be valid the factorization must have been performed with at least SVDFullU.
Example ¶
package main import ( "fmt" "log" "gonum.org/v1/gonum/mat" ) func main() { // The system described by A is rank deficient. a := mat.NewDense(5, 3, []float64{ -1.7854591879711257, -0.42687285925779594, -0.12730256811265162, -0.5728984211439724, -0.10093393134001777, -0.1181901192353067, 1.2484316018707418, 0.5646683943038734, -0.48229492403243485, 0.10174927665169475, -0.5805410929482445, 1.3054473231942054, -1.134174808195733, -0.4732430202414438, 0.3528489486370508, }) // Perform an SVD retaining all singular vectors. var svd mat.SVD ok := svd.Factorize(a, mat.SVDFull) if !ok { log.Fatal("failed to factorize A") } // Determine the rank of the A matrix with a near zero condition threshold. const rcond = 1e-15 rank := svd.Rank(rcond) if rank == 0 { log.Fatal("zero rank system") } b := mat.NewVecDense(5, []float64{-2.318, -0.715, 1.836, -0.357, -1.636}) // Find a least-squares solution using the determined parts of the system. var x mat.VecDense svd.SolveVecTo(&x, b, rank) fmt.Printf("singular values = %v\nrank = %d\nx = %.15f", format(svd.Values(nil), 4, rcond), rank, mat.Formatted(&x, mat.Prefix(" "))) } func format(vals []float64, prec int, eps float64) []string { s := make([]string, len(vals)) for i, v := range vals { if v < eps { s[i] = fmt.Sprintf("<%.*g", prec, eps) continue } s[i] = fmt.Sprintf("%.*g", prec, v) } return s }
Output: singular values = [2.685 1.526 <1e-15] rank = 2 x = ⎡ 1.212064313552347⎤ ⎢ 0.415400738264774⎥ ⎣-0.183184442255280⎦
func (*SVD) UTo ¶
UTo extracts the matrix U from the singular value decomposition. The first min(m,n) columns are the left singular vectors and correspond to the singular values as returned from SVD.Values.
If dst is empty, UTo will resize dst to be m×m if the full U was computed and size m×min(m,n) if the thin U was computed. When dst is non-empty, then UTo will panic if dst is not the appropriate size. UTo will also panic if the receiver does not contain a successful factorization, or if U was not computed during factorization.
func (*SVD) VTo ¶
VTo extracts the matrix V from the singular value decomposition. The first min(m,n) columns are the right singular vectors and correspond to the singular values as returned from SVD.Values.
If dst is empty, VTo will resize dst to be n×n if the full V was computed and size n×min(m,n) if the thin V was computed. When dst is non-empty, then VTo will panic if dst is not the appropriate size. VTo will also panic if the receiver does not contain a successful factorization, or if V was not computed during factorization.
func (*SVD) Values ¶
Values returns the singular values of the factorized matrix in descending 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 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 SVDKind ¶
type SVDKind int
SVDKind specifies the treatment of singular vectors during an SVD factorization.
const ( // SVDNone specifies that no singular vectors should be computed during // the decomposition. SVDNone SVDKind = 0 // SVDThinU specifies the thin decomposition for U should be computed. SVDThinU SVDKind = 1 << (iota - 1) // SVDFullU specifies the full decomposition for U should be computed. SVDFullU // SVDThinV specifies the thin decomposition for V should be computed. SVDThinV // SVDFullV specifies the full decomposition for V should be computed. SVDFullV // SVDThin is a convenience value for computing both thin vectors. SVDThin SVDKind = SVDThinU | SVDThinV // SVDFull is a convenience value for computing both full vectors. SVDFull SVDKind = SVDFullU | SVDFullV )
type SymBandDense ¶
type SymBandDense struct {
// contains filtered or unexported fields
}
SymBandDense represents a symmetric band matrix in dense storage format.
func NewSymBandDense ¶
func NewSymBandDense(n, k int, data []float64) *SymBandDense
NewSymBandDense creates a new SymBand matrix with n rows and columns. If data == nil, a new slice is allocated for the backing slice. If len(data) == n*(k+1), data is used as the backing slice, and changes to the elements of the returned SymBandDense will be reflected in data. If neither of these is true, NewSymBandDense will panic. k must be at least zero and less than n, otherwise NewSymBandDense will panic.
The data must be arranged in row-major order constructed by removing the zeros from the rows outside the band and aligning the diagonals. SymBandDense matrices are stored in the upper triangle. For example, the matrix
1 2 3 0 0 0 2 4 5 6 0 0 3 5 7 8 9 0 0 6 8 10 11 12 0 0 9 11 13 14 0 0 0 12 14 15
becomes (* entries are never accessed)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 * 15 * *
which is passed to NewSymBandDense as []float64{1, 2, ..., 15, *, *, *} with k=2. Only the values in the band portion of the matrix are used.
func (*SymBandDense) At ¶
func (s *SymBandDense) At(i, j int) float64
At returns the element at row i, column j.
func (*SymBandDense) Bandwidth ¶
func (s *SymBandDense) Bandwidth() (kl, ku int)
Bandwidth returns the bandwidths of the matrix.
func (*SymBandDense) DiagView ¶
func (s *SymBandDense) DiagView() Diagonal
DiagView returns the diagonal as a matrix backed by the original data.
func (*SymBandDense) Dims ¶
func (s *SymBandDense) Dims() (r, c int)
Dims returns the number of rows and columns in the matrix.
func (*SymBandDense) DoColNonZero ¶
func (s *SymBandDense) DoColNonZero(j int, fn func(i, j int, v float64))
DoColNonZero calls the function fn for each of the non-zero elements of column j of s. The function fn takes a row/column index and the element value of s at (i, j).
func (*SymBandDense) DoNonZero ¶
func (s *SymBandDense) DoNonZero(fn func(i, j int, v float64))
DoNonZero calls the function fn for each of the non-zero elements of s. The function fn takes a row/column index and the element value of s at (i, j).
func (*SymBandDense) DoRowNonZero ¶
func (s *SymBandDense) DoRowNonZero(i int, fn func(i, j int, v float64))
DoRowNonZero calls the function fn for each of the non-zero elements of row i of s. The function fn takes a row/column index and the element value of s at (i, j).
func (*SymBandDense) IsEmpty ¶
func (s *SymBandDense) IsEmpty() bool
IsEmpty returns whether the receiver is empty. Empty matrices can be the receiver for size-restricted operations. The receiver can be emptied using Reset.
func (*SymBandDense) MulVecTo ¶
func (s *SymBandDense) MulVecTo(dst *VecDense, _ bool, x Vector)
MulVecTo computes S⋅x storing the result into dst.
func (*SymBandDense) RawSymBand ¶
func (s *SymBandDense) RawSymBand() blas64.SymmetricBand
RawSymBand returns the underlying blas64.SymBand used by the receiver. Changes to elements in the receiver following the call will be reflected in returned blas64.SymBand.
func (*SymBandDense) Reset ¶
func (s *SymBandDense) Reset()
Reset empties the matrix so that it can be reused as the receiver of a dimensionally restricted operation.
Reset should not be used when the matrix shares backing data. See the Reseter interface for more information.
func (*SymBandDense) SetRawSymBand ¶
func (s *SymBandDense) SetRawSymBand(mat blas64.SymmetricBand)
SetRawSymBand sets the underlying blas64.SymmetricBand used by the receiver. Changes to elements in the receiver following the call will be reflected in the input.
The supplied SymmetricBand must use blas.Upper storage format.
func (*SymBandDense) SetSymBand ¶
func (s *SymBandDense) SetSymBand(i, j int, v float64)
SetSymBand sets the element at row i, column j to the value v. It panics if the location is outside the appropriate region of the matrix.
func (*SymBandDense) SymBand ¶
func (s *SymBandDense) SymBand() (n, k int)
SymBand returns the number of rows/columns in the matrix, and the size of the bandwidth.
func (*SymBandDense) Symmetric ¶
func (s *SymBandDense) Symmetric() int
Symmetric returns the size of the receiver.
func (*SymBandDense) T ¶
func (s *SymBandDense) T() Matrix
T implements the Matrix interface. Symmetric matrices, by definition, are equal to their transpose, and this is a no-op.
func (*SymBandDense) TBand ¶
func (s *SymBandDense) TBand() Banded
TBand implements the Banded interface.
func (*SymBandDense) Zero ¶
func (s *SymBandDense) Zero()
Zero sets all of the matrix elements to zero.
type SymBanded ¶
type SymBanded interface { Banded // Symmetric returns the number of rows/columns in the matrix. Symmetric() int // SymBand returns the number of rows/columns in the matrix, and the size of // the bandwidth. SymBand() (n, k int) }
SymBanded is a symmetric band matrix interface type.
type SymDense ¶
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.
func NewSymDense ¶
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. NewSymDense will panic if n is zero.
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.
func (*SymDense) GrowSym ¶
GrowSym 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.
func (*SymDense) IsEmpty ¶
IsEmpty returns whether the receiver is empty. Empty matrices can be the receiver for size-restricted operations. The receiver can be emptied using Reset.
func (*SymDense) PowPSD ¶
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 Eigen decomposition is not successful.
func (*SymDense) RankTwo ¶
RankTwo performs a symmetric rank-two update to the matrix a with the vectors x and y, which are treated as column vectors, and stores the result in the receiver
m = a + alpha * (x * yᵀ + y * xᵀ)
func (*SymDense) RawSymmetric ¶
RawSymmetric returns the matrix as a blas64.Symmetric. The returned value must be stored in upper triangular format.
func (*SymDense) Reset ¶
func (s *SymDense) Reset()
Reset empties the matrix so that it can be reused as the receiver of a dimensionally restricted operation.
Reset should not be used when the matrix shares backing data. See the Reseter interface for more information.
func (*SymDense) ReuseAsSym ¶
ReuseAsSym changes the receiver if it IsEmpty() to be of size n×n.
ReuseAsSym re-uses the backing data slice if it has sufficient capacity, otherwise a new slice is allocated. The backing data is zero on return.
ReuseAsSym panics if the receiver is not empty, and panics if the input size is less than one. To empty the receiver for re-use, Reset should be used.
func (*SymDense) ScaleSym ¶
ScaleSym multiplies the elements of a by f, placing the result in the receiver.
func (*SymDense) SetRawSymmetric ¶
SetRawSymmetric sets the underlying blas64.Symmetric used by the receiver. Changes to elements in the receiver following the call will be reflected in the input.
The supplied Symmetric must use blas.Upper storage format.
func (*SymDense) SliceSym ¶
SliceSym returns a new Matrix that shares backing data with the receiver. The returned matrix starts at {i,i} of the receiver and extends k-i rows and columns. The final row and column in the resulting matrix is k-1. SliceSym panics with ErrIndexOutOfRange if the slice is outside the capacity of the receiver.
func (*SymDense) SubsetSym ¶
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.
Example ¶
package main import ( "fmt" "gonum.org/v1/gonum/mat" ) func main() { n := 5 s := mat.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", mat.Formatted(s)) // Take the subset {0, 2, 4} var sub mat.SymDense sub.SubsetSym(s, []int{0, 2, 4}) fmt.Println("Subset {0, 2, 4}") fmt.Printf("%0.4v\n\n", mat.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", mat.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⎦
func (*SymDense) SymOuterK ¶
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.
func (*SymDense) SymRankK ¶
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'
func (*SymDense) SymRankOne ¶
SymRankOne performs a symmetric rank-one update to the matrix a with x, which is treated as a column vector, and stores the result in the receiver
s = a + alpha * x * xᵀ
func (*SymDense) Symmetric ¶
Symmetric implements the Symmetric interface and returns the number of rows and columns in the matrix.
type Symmetric ¶
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.
type Tracer ¶
type Tracer interface {
Trace() float64
}
A Tracer can compute the trace of the matrix. Trace must panic if the matrix is not square.
type Transpose ¶
type Transpose struct {
Matrix Matrix
}
Transpose is a type for performing an implicit matrix transpose. It implements the Matrix interface, returning values from the transpose of the matrix within.
func (Transpose) At ¶
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.
func (Transpose) Dims ¶
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.
func (Transpose) Untranspose ¶
Untranspose returns the Matrix field.
type TransposeBand ¶
type TransposeBand struct {
Banded Banded
}
TransposeBand is a type for performing an implicit transpose of a band matrix. It implements the Banded interface, returning values from the transpose of the matrix within.
func (TransposeBand) At ¶
func (t TransposeBand) 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 Banded field.
func (TransposeBand) Bandwidth ¶
func (t TransposeBand) Bandwidth() (kl, ku int)
Bandwidth returns the lower and upper bandwidth values for the transposed matrix.
func (TransposeBand) Dims ¶
func (t TransposeBand) Dims() (r, c int)
Dims returns the dimensions of the transposed matrix.
func (TransposeBand) T ¶
func (t TransposeBand) T() Matrix
T performs an implicit transpose by returning the Banded field.
func (TransposeBand) TBand ¶
func (t TransposeBand) TBand() Banded
TBand performs an implicit transpose by returning the Banded field.
func (TransposeBand) Untranspose ¶
func (t TransposeBand) Untranspose() Matrix
Untranspose returns the Banded field.
func (TransposeBand) UntransposeBand ¶
func (t TransposeBand) UntransposeBand() Banded
UntransposeBand returns the Banded field.
type TransposeTri ¶
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 (TransposeTri) At ¶
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 (TransposeTri) Dims ¶
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 (TransposeTri) T ¶
func (t TransposeTri) T() Matrix
T performs an implicit transpose by returning the Triangular field.
func (TransposeTri) TTri ¶
func (t TransposeTri) TTri() Triangular
TTri performs an implicit transpose by returning the Triangular field.
func (TransposeTri) Triangle ¶
func (t TransposeTri) Triangle() (int, TriKind)
Triangle returns the number of rows/columns in the matrix and its orientation.
func (TransposeTri) Untranspose ¶
func (t TransposeTri) Untranspose() Matrix
Untranspose returns the Triangular field.
func (TransposeTri) UntransposeTri ¶
func (t TransposeTri) UntransposeTri() Triangular
type TransposeTriBand ¶
type TransposeTriBand struct {
TriBanded TriBanded
}
TransposeTriBand is a type for performing an implicit transpose of a TriBanded matrix. It implements the TriBanded interface, returning values from the transpose of the matrix within.
func (TransposeTriBand) At ¶
func (t TransposeTriBand) 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 TriBanded field.
func (TransposeTriBand) Bandwidth ¶
func (t TransposeTriBand) Bandwidth() (kl, ku int)
Bandwidth returns the upper and lower bandwidths of the matrix.
func (TransposeTriBand) Dims ¶
func (t TransposeTriBand) Dims() (r, c int)
Dims returns the dimensions of the transposed matrix. TriBanded matrices are square and thus this is the same size as the original TriBanded.
func (TransposeTriBand) T ¶
func (t TransposeTriBand) T() Matrix
T performs an implicit transpose by returning the TriBand field.
func (TransposeTriBand) TBand ¶
func (t TransposeTriBand) TBand() Banded
TBand performs an implicit transpose by returning the TriBand field.
func (TransposeTriBand) TTri ¶
func (t TransposeTriBand) TTri() Triangular
TTri performs an implicit transpose by returning the TriBand field.
func (TransposeTriBand) TTriBand ¶
func (t TransposeTriBand) TTriBand() TriBanded
TTriBand performs an implicit transpose by returning the TriBand field.
func (TransposeTriBand) TriBand ¶
func (t TransposeTriBand) TriBand() (n, k int, kind TriKind)
TriBand returns the number of rows/columns in the matrix, the size of the bandwidth, and the orientation.
func (TransposeTriBand) Triangle ¶
func (t TransposeTriBand) Triangle() (int, TriKind)
Triangle returns the number of rows/columns in the matrix and its orientation.
func (TransposeTriBand) Untranspose ¶
func (t TransposeTriBand) Untranspose() Matrix
Untranspose returns the Triangular field.
func (TransposeTriBand) UntransposeBand ¶
func (t TransposeTriBand) UntransposeBand() Banded
UntransposeBand returns the underlying Banded matrix.
func (TransposeTriBand) UntransposeTri ¶
func (t TransposeTriBand) UntransposeTri() Triangular
UntransposeTri returns the underlying Triangular matrix.
func (TransposeTriBand) UntransposeTriBand ¶
func (t TransposeTriBand) UntransposeTriBand() TriBanded
UntransposeTriBand returns the underlying TriBanded matrix.
type TransposeVec ¶
type TransposeVec struct {
Vector Vector
}
TransposeVec is a type for performing an implicit transpose of a Vector. It implements the Vector interface, returning values from the transpose of the vector within.
func (TransposeVec) At ¶
func (t TransposeVec) 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 Vector field.
func (TransposeVec) AtVec ¶
func (t TransposeVec) AtVec(i int) float64
AtVec returns the element at position i. It panics if i is out of bounds.
func (TransposeVec) Dims ¶
func (t TransposeVec) Dims() (r, c int)
Dims returns the dimensions of the transposed vector.
func (TransposeVec) Len ¶
func (t TransposeVec) Len() int
Len returns the number of columns in the vector.
func (TransposeVec) T ¶
func (t TransposeVec) T() Matrix
T performs an implicit transpose by returning the Vector field.
func (TransposeVec) TVec ¶
func (t TransposeVec) TVec() Vector
TVec performs an implicit transpose by returning the Vector field.
func (TransposeVec) Untranspose ¶
func (t TransposeVec) Untranspose() Matrix
Untranspose returns the Vector field.
func (TransposeVec) UntransposeVec ¶
func (t TransposeVec) UntransposeVec() Vector
type TriBandDense ¶
type TriBandDense struct {
// contains filtered or unexported fields
}
TriBandDense represents a triangular band matrix in dense storage format.
func NewTriBandDense ¶
func NewTriBandDense(n, k int, kind TriKind, data []float64) *TriBandDense
NewTriBandDense creates a new triangular banded matrix with n rows and columns, k bands in the direction of the specified kind. If data == nil, a new slice is allocated for the backing slice. If len(data) == n*(k+1), data is used as the backing slice, and changes to the elements of the returned TriBandDense will be reflected in data. If neither of these is true, NewTriBandDense will panic. k must be at least zero and less than n, otherwise NewTriBandDense will panic.
The data must be arranged in row-major order constructed by removing the zeros from the rows outside the band and aligning the diagonals. For example, if the upper-triangular banded matrix
1 2 3 0 0 0 0 4 5 6 0 0 0 0 7 8 9 0 0 0 0 10 11 12 0 0 0 0 13 14 0 0 0 0 0 15
becomes (* entries are never accessed)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 * 15 * *
which is passed to NewTriBandDense as []float64{1, 2, ..., 15, *, *, *} with k=2 and kind = mat.Upper. The lower triangular banded matrix
1 0 0 0 0 0 2 3 0 0 0 0 4 5 6 0 0 0 0 7 8 9 0 0 0 0 10 11 12 0 0 0 0 13 14 15
becomes (* entries are never accessed)
- * 1
- 2 3 4 5 6 7 8 9 10 11 12 13 14 15
which is passed to NewTriBandDense as []float64{*, *, *, 1, 2, ..., 15} with k=2 and kind = mat.Lower. Only the values in the band portion of the matrix are used.
func (*TriBandDense) At ¶
func (t *TriBandDense) At(i, j int) float64
func (*TriBandDense) Bandwidth ¶
func (t *TriBandDense) Bandwidth() (kl, ku int)
Bandwidth returns the upper and lower bandwidths of the matrix.
func (*TriBandDense) DiagView ¶
func (t *TriBandDense) DiagView() Diagonal
DiagView returns the diagonal as a matrix backed by the original data.
func (*TriBandDense) Dims ¶
func (t *TriBandDense) Dims() (r, c int)
Dims returns the number of rows and columns in the matrix.
func (*TriBandDense) IsEmpty ¶
func (t *TriBandDense) IsEmpty() bool
IsEmpty returns whether the receiver is empty. Empty matrices can be the receiver for size-restricted operations. The receiver can be emptied using Reset.
func (*TriBandDense) RawTriBand ¶
func (t *TriBandDense) RawTriBand() blas64.TriangularBand
RawTriBand returns the underlying blas64.TriangularBand used by the receiver. Changes to the blas64.TriangularBand.Data slice will be reflected in the original matrix, changes to the N, K, Stride, Uplo and Diag fields will not.
func (*TriBandDense) Reset ¶
func (t *TriBandDense) Reset()
Reset empties the matrix so that it can be reused as the receiver of a dimensionally restricted operation.
Reset should not be used when the matrix shares backing data. See the Reseter interface for more information.
func (*TriBandDense) ReuseAsTriBand ¶
func (t *TriBandDense) ReuseAsTriBand(n, k int, kind TriKind)
ReuseAsTriBand changes the receiver to be of size n×n, bandwidth k+1 and of the given kind, re-using the backing data slice if it has sufficient capacity and allocating a new slice otherwise. The backing data is zero on return.
The receiver must be empty, n must be positive and k must be non-negative and less than n, otherwise ReuseAsTriBand will panic. To empty the receiver for re-use, Reset should be used.
func (*TriBandDense) SetRawTriBand ¶
func (t *TriBandDense) SetRawTriBand(mat blas64.TriangularBand)
SetRawTriBand sets the underlying blas64.TriangularBand used by the receiver. Changes to elements in the receiver following the call will be reflected in the input.
The supplied TriangularBand must not use blas.Unit storage format.
func (*TriBandDense) SetTriBand ¶
func (t *TriBandDense) SetTriBand(i, j int, v float64)
func (*TriBandDense) SolveTo ¶
func (t *TriBandDense) SolveTo(dst *Dense, trans bool, b Matrix) error
SolveTo solves a triangular system T * X = B or Tᵀ * X = B where T is an n×n triangular band matrix represented by the receiver and B is a given n×nrhs matrix. If T is non-singular, the result will be stored into dst and nil will be returned. If T is singular, the contents of dst will be undefined and a Condition error will be returned.
func (*TriBandDense) SolveVecTo ¶
func (t *TriBandDense) SolveVecTo(dst *VecDense, trans bool, b Vector) error
SolveVecTo solves a triangular system T * x = b or Tᵀ * x = b where T is an n×n triangular band matrix represented by the receiver and b is a given n-vector. If T is non-singular, the result will be stored into dst and nil will be returned. If T is singular, the contents of dst will be undefined and a Condition error will be returned.
func (*TriBandDense) T ¶
func (t *TriBandDense) T() Matrix
T performs an implicit transpose by returning the receiver inside a Transpose.
func (*TriBandDense) TBand ¶
func (t *TriBandDense) TBand() Banded
TBand performs an implicit transpose by returning the receiver inside a TransposeBand.
func (*TriBandDense) TTri ¶
func (t *TriBandDense) TTri() Triangular
TTri performs an implicit transpose by returning the receiver inside a TransposeTri.
func (*TriBandDense) TTriBand ¶
func (t *TriBandDense) TTriBand() TriBanded
TTriBand performs an implicit transpose by returning the receiver inside a TransposeTriBand.
func (*TriBandDense) TriBand ¶
func (t *TriBandDense) TriBand() (n, k int, kind TriKind)
TriBand returns the number of rows/columns in the matrix, the size of the bandwidth, and the orientation.
func (*TriBandDense) Triangle ¶
func (t *TriBandDense) Triangle() (n int, kind TriKind)
Triangle returns the dimension of t and its orientation. The returned orientation is only valid when n is not zero.
func (*TriBandDense) Zero ¶
func (t *TriBandDense) Zero()
Zero sets all of the matrix elements to zero.
type TriBanded ¶
type TriBanded interface { Banded // Triangle returns the number of rows/columns in the matrix and its // orientation. Triangle() (n int, kind TriKind) // TTri is the equivalent of the T() method in the Matrix interface but // guarantees the transpose is of triangular type. TTri() Triangular // TriBand returns the number of rows/columns in the matrix, the // size of the bandwidth, and the orientation. TriBand() (n, k int, kind TriKind) // TTriBand is the equivalent of the T() method in the Matrix interface but // guarantees the transpose is of banded triangular type. TTriBand() TriBanded }
TriBanded is a triangular band matrix interface type.
type TriDense ¶
type TriDense struct {
// contains filtered or unexported fields
}
TriDense represents an upper or lower triangular matrix in dense storage format.
func NewTriDense ¶
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. NewTriDense will panic if n is zero.
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.
func (*TriDense) Copy ¶
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 (*TriDense) DoColNonZero ¶
DoColNonZero calls the function fn for each of the non-zero elements of column j of t. The function fn takes a row/column index and the element value of t at (i, j).
func (*TriDense) DoNonZero ¶
DoNonZero calls the function fn for each of the non-zero elements of t. The function fn takes a row/column index and the element value of t at (i, j).
func (*TriDense) DoRowNonZero ¶
DoRowNonZero calls the function fn for each of the non-zero elements of row i of t. The function fn takes a row/column index and the element value of t at (i, j).
func (*TriDense) InverseTri ¶
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.
func (*TriDense) IsEmpty ¶
IsEmpty returns whether the receiver is empty. Empty matrices can be the receiver for size-restricted operations. The receiver can be emptied using Reset.
func (*TriDense) MulTri ¶
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 (*TriDense) RawTriangular ¶
func (t *TriDense) RawTriangular() blas64.Triangular
func (*TriDense) Reset ¶
func (t *TriDense) Reset()
Reset empties the matrix so that it can be reused as the receiver of a dimensionally restricted operation.
Reset should not be used when the matrix shares backing data. See the Reseter interface for more information.
func (*TriDense) ReuseAsTri ¶
ReuseAsTri changes the receiver if it IsEmpty() to be of size n×n.
ReuseAsTri re-uses the backing data slice if it has sufficient capacity, otherwise a new slice is allocated. The backing data is zero on return.
ReuseAsTri panics if the receiver is not empty, and panics if the input size is less than one. To empty the receiver for re-use, Reset should be used.
func (*TriDense) ScaleTri ¶
func (t *TriDense) ScaleTri(f float64, a Triangular)
ScaleTri multiplies the elements of a by f, placing the result in the receiver. If the receiver is non-zero, the size and kind of the receiver must match the input, or ScaleTri will panic.
func (*TriDense) SetRawTriangular ¶
func (t *TriDense) SetRawTriangular(mat blas64.Triangular)
SetRawTriangular sets the underlying blas64.Triangular used by the receiver. Changes to elements in the receiver following the call will be reflected in the input.
The supplied Triangular must not use blas.Unit storage format.
func (*TriDense) SetTri ¶
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.
func (*TriDense) SliceTri ¶
func (t *TriDense) SliceTri(i, k int) Triangular
SliceTri returns a new Triangular that shares backing data with the receiver. The returned matrix starts at {i,i} of the receiver and extends k-i rows and columns. The final row and column in the resulting matrix is k-1. SliceTri panics with ErrIndexOutOfRange if the slice is outside the capacity of the receiver.
func (*TriDense) TTri ¶
func (t *TriDense) TTri() Triangular
TTri performs an implicit transpose by returning the receiver inside a TransposeTri.
type Triangular ¶
type Triangular interface { Matrix // Triangle returns the number of rows/columns in the matrix and its // orientation. Triangle() (n int, kind TriKind) // TTri is the equivalent of the T() method in the Matrix interface but // guarantees the transpose is of triangular type. TTri() Triangular }
Triangular represents a triangular matrix. Triangular matrices are always square.
type UnConjTransposer ¶
type UnConjTransposer interface { // UnConjTranspose returns the underlying CMatrix stored for the implicit // conjugate transpose. UnConjTranspose() CMatrix }
UnConjTransposer is a type that can undo an implicit conjugate transpose.
type UntransposeBander ¶
type UntransposeBander interface { // Untranspose returns the underlying Banded stored for the implicit transpose. UntransposeBand() Banded }
UntransposeBander is a type that can undo an implicit band transpose.
type UntransposeTriBander ¶
type UntransposeTriBander interface { // Untranspose returns the underlying Triangular stored for the implicit transpose. UntransposeTriBand() TriBanded }
UntransposeTriBander is a type that can undo an implicit triangular banded transpose.
type UntransposeTrier ¶
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 ¶
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 VecDense ¶
type VecDense struct {
// contains filtered or unexported fields
}
VecDense represents a column vector.
func NewVecDense ¶
NewVecDense creates a new VecDense 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 VecDense will be reflected in data. If neither of these is true, NewVecDense will panic. NewVecDense will panic if n is zero.
func VecDenseCopyOf ¶
VecDenseCopyOf returns a newly allocated copy of the elements of a.
func (*VecDense) AddScaledVec ¶
AddScaledVec adds the vectors a and alpha*b, placing the result in the receiver.
func (*VecDense) At ¶
At returns the element at row i. It panics if i is out of bounds or if j is not zero.
func (*VecDense) Caps ¶
Caps returns the number of rows and columns in the backing matrix. Columns is always 1 for a non-Reset vector.
func (*VecDense) CloneFromVec ¶
CloneFromVec makes a copy of a into the receiver, overwriting the previous value of the receiver.
func (*VecDense) ColViewOf ¶
func (v *VecDense) ColViewOf(m RawMatrixer, j int)
ColViewOf reflects the column j of the RawMatrixer m, into the receiver backed by the same underlying data. The receiver must either be empty have length equal to the number of rows of m.
func (*VecDense) CopyVec ¶
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.
func (*VecDense) Dims ¶
Dims returns the number of rows and columns in the matrix. Columns is always 1 for a non-Reset vector.
func (*VecDense) DivElemVec ¶
DivElemVec performs element-wise division of a by b, placing the result in the receiver.
func (*VecDense) IsEmpty ¶
IsEmpty returns whether the receiver is empty. Empty matrices can be the receiver for size-restricted operations. The receiver can be emptied using Reset.
func (VecDense) MarshalBinary ¶
MarshalBinary encodes the receiver into a binary form and returns the result.
VecDense is little-endian encoded as follows:
0 - 3 Version = 1 (uint32) 4 'G' (byte) 5 'F' (byte) 6 'A' (byte) 7 0 (byte) 8 - 15 number of elements (int64) 16 - 23 1 (int64) 24 - 31 0 (int64) 32 - 39 0 (int64) 40 - .. vector's data elements (float64)
func (VecDense) MarshalBinaryTo ¶
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.
func (*VecDense) MulElemVec ¶
MulElemVec performs element-wise multiplication of a and b, placing the result in the receiver.
func (*VecDense) MulVec ¶
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 or if the number of columns in b does not equal 1.
func (*VecDense) RawVector ¶
RawVector returns the underlying blas64.Vector used by the receiver. Changes to elements in the receiver following the call will be reflected in returned blas64.Vector.
func (*VecDense) Reset ¶
func (v *VecDense) Reset()
Reset empties the matrix so that it can be reused as the receiver of a dimensionally restricted operation.
Reset should not be used when the matrix shares backing data. See the Reseter interface for more information.
func (*VecDense) ReuseAsVec ¶
ReuseAsVec changes the receiver if it IsEmpty() to be of size n×1.
ReuseAsVec re-uses the backing data slice if it has sufficient capacity, otherwise a new slice is allocated. The backing data is zero on return.
ReuseAsVec panics if the receiver is not empty, and panics if the input size is less than one. To empty the receiver for re-use, Reset should be used.
func (*VecDense) RowViewOf ¶
func (v *VecDense) RowViewOf(m RawMatrixer, i int)
RowViewOf reflects the row i of the RawMatrixer m, into the receiver backed by the same underlying data. The receiver must either be empty or have length equal to the number of columns of m.
func (*VecDense) ScaleVec ¶
ScaleVec scales the vector a by alpha, placing the result in the receiver.
func (*VecDense) SetRawVector ¶
SetRawVector sets the underlying blas64.Vector used by the receiver. Changes to elements in the receiver following the call will be reflected in the input.
func (*VecDense) SetVec ¶
SetVec sets the element at row i to the value val. It panics if i is out of bounds.
func (*VecDense) SliceVec ¶
SliceVec returns a new Vector that shares backing data with the receiver. The returned matrix starts at i of the receiver and extends k-i elements. SliceVec panics with ErrIndexOutOfRange if the slice is outside the capacity of the receiver.
func (*VecDense) SolveVec ¶
SolveVec solves the linear least squares problem
minimize over x |b - A*x|_2
where A is an m×n matrix A, b is a given m element vector and x is n element solution vector. Solve assumes that A has full rank, that is
rank(A) = min(m,n)
If m >= n, Solve finds the unique least squares solution of an overdetermined system.
If m < n, there is an infinite number of solutions that satisfy b-A*x=0. In this case Solve finds the unique solution of an underdetermined system that minimizes |x|_2.
The solution vector x will be stored in-place into the receiver.
If A does not have full rank, a Condition error is returned. See the documentation for Condition for more information.
func (*VecDense) TVec ¶
TVec performs an implicit transpose by returning the receiver inside a TransposeVec.
func (*VecDense) UnmarshalBinary ¶
UnmarshalBinary decodes the binary form into the receiver. It panics if the receiver is a non-empty VecDense.
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 VecDense 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.
func (*VecDense) UnmarshalBinaryFrom ¶
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-empty VecDense.
See MarshalBinary for the on-disk layout. See UnmarshalBinary for the list of sanity checks performed on the input.
Notes ¶
Bugs ¶
The computation of the 1-norm and ∞-norm for non-square matrices is inaccurate, 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.
Source Files ¶
- band.go
- cdense.go
- cholesky.go
- cmatrix.go
- consts.go
- dense.go
- dense_arithmetic.go
- diagonal.go
- doc.go
- eigen.go
- errors.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
- shadow_common.go
- shadow_complex.go
- solve.go
- svd.go
- symband.go
- symmetric.go
- triangular.go
- triband.go
- vector.go