mat64

package
v0.0.0-...-dfba71b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 9, 2020 License: BSD-2-Clause Imports: 15 Imported by: 0

Documentation

Overview

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

Overview

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

mat64 provides:

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

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

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

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

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

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

tr := mat64.Trace(a)

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

zero.Copy(a)

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

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

The Matrix Interfaces

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

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

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

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

the Symmetric interface guarantees a symmetric result.

Transposes

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

Matrix 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 mat64.LU
lu.Factorize(a)

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

BLAS and LAPACK

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

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 *Vector blas64.Gemv is used.

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

Invariants

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

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

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

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

Element Aliasing

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

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

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

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

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

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

The following cases will not panic:

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

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

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Col

func Col(dst []float64, j int, a Matrix) []float64

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.

func Cond

func Cond(a Matrix, norm float64) float64

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

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

func Det

func Det(a Matrix) float64

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

func Dot

func Dot(a, b *Vector) float64

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

func Equal

func Equal(a, b Matrix) bool

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

func EqualApprox

func EqualApprox(a, b Matrix, epsilon float64) bool

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"

	"github.com/gonum/matrix/mat64"
)

func main() {
	a := mat64.NewDense(3, 3, []float64{1, 2, 3, 0, 4, 5, 0, 0, 6})

	// Create a matrix formatting value with a prefix and calculating each column
	// width individually...
	fa := mat64.Formatted(a, mat64.Prefix("    "), mat64.Squeeze())

	// and then print with and without zero value elements.
	fmt.Printf("with all values:\na = %v\n\n", fa)
	fmt.Printf("with only non-zero values:\na = % v\n\n", fa)

	// Modify the matrix...
	a.Set(0, 2, 0)

	// and print it without zero value elements.
	fmt.Printf("after modification with only non-zero values:\na = % v\n\n", fa)

	// Modify the matrix again...
	a.Set(0, 2, 123.456)

	// and print it using scientific notation for large exponents.
	fmt.Printf("after modification with scientific notation:\na = %.2g\n\n", fa)
	// See golang.org/pkg/fmt/ floating-point verbs for a comprehensive list.

}
Output:

with all values:
a = ⎡1  2  3⎤
    ⎢0  4  5⎥
    ⎣0  0  6⎦

with only non-zero values:
a = ⎡1  2  3⎤
    ⎢.  4  5⎥
    ⎣.  .  6⎦

after modification with only non-zero values:
a = ⎡1  2  .⎤
    ⎢.  4  5⎥
    ⎣.  .  6⎦

after modification with scientific notation:
a = ⎡1  2  1.2e+02⎤
    ⎢0  4        5⎥
    ⎣0  0        6⎦

func Inner

func Inner(x *Vector, A Matrix, y *Vector) float64

Inner computes the generalized inner product

x^T A y

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

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

func LogDet

func LogDet(a Matrix) (det float64, sign float64)

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

func Max(a Matrix) float64

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

func Min

func Min(a Matrix) float64

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

func Norm

func Norm(a Matrix, norm float64) float64

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

Valid norms are:

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

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

func Row

func Row(dst []float64, i int, a Matrix) []float64

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

func Sum

func Sum(a Matrix) float64

Sum returns the sum of the elements of the matrix.

func Trace

func Trace(a Matrix) float64

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

Types

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 Cholesky

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

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

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

Example
package main

import (
	"fmt"

	"github.com/gonum/matrix/mat64"
)

func main() {
	// Construct a symmetric positive definite matrix.
	tmp := mat64.NewDense(4, 4, []float64{
		2, 6, 8, -4,
		1, 8, 7, -2,
		2, 2, 1, 7,
		8, -2, -2, 1,
	})
	var a mat64.SymDense
	a.SymOuterK(1, tmp)

	fmt.Printf("a = %0.4v\n", mat64.Formatted(&a, mat64.Prefix("    ")))

	// Compute the cholesky factorization.
	var chol mat64.Cholesky
	if ok := chol.Factorize(&a); !ok {
		fmt.Println("a matrix is not positive semi-definite.")
	}

	// Find the determinant.
	fmt.Printf("\nThe determinant of a is %0.4g\n\n", chol.Det())

	// Use the factorization to solve the system of equations a * x = b.
	b := mat64.NewVector(4, []float64{1, 2, 3, 4})
	var x mat64.Vector
	if err := x.SolveCholeskyVec(&chol, b); err != nil {
		fmt.Println("Matrix is near singular: ", err)
	}
	fmt.Println("Solve a * x = b")
	fmt.Printf("x = %0.4v\n", mat64.Formatted(&x, mat64.Prefix("    ")))

	// Extract the factorization and check that it equals the original matrix.
	var t mat64.TriDense
	t.LFromCholesky(&chol)
	var test mat64.Dense
	test.Mul(&t, t.T())
	fmt.Println()
	fmt.Printf("L * L^T = %0.4v\n", mat64.Formatted(&a, mat64.Prefix("          ")))

}
Output:

a = ⎡120  114   -4  -16⎤
    ⎢114  118   11  -24⎥
    ⎢ -4   11   58   17⎥
    ⎣-16  -24   17   73⎦

The determinant of a is 1.543e+06

Solve a * x = b
x = ⎡  -0.239⎤
    ⎢  0.2732⎥
    ⎢-0.04681⎥
    ⎣  0.1031⎦

L * L^T = ⎡120  114   -4  -16⎤
          ⎢114  118   11  -24⎥
          ⎢ -4   11   58   17⎥
          ⎣-16  -24   17   73⎦

func (*Cholesky) Clone

func (c *Cholesky) Clone(chol *Cholesky)

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) Det

func (c *Cholesky) Det() float64

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

func (*Cholesky) Factorize

func (c *Cholesky) Factorize(a Symmetric) (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 (*Cholesky) LogDet

func (c *Cholesky) LogDet() float64

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

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) SetFromU

func (c *Cholesky) SetFromU(t *TriDense)

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

func (*Cholesky) Size

func (c *Cholesky) Size() int

Size returns the dimension of the factorized matrix.

func (*Cholesky) SymRankOne

func (c *Cholesky) SymRankOne(orig *Cholesky, alpha float64, x *Vector) (ok bool)

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

U^T * U = A,

in the updated factorization

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

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

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

type Cloner

type Cloner interface {
	Clone(a Matrix)
}

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

type ColViewer

type ColViewer interface {
	ColView(j int) *Vector
}

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 Copier

type Copier interface {
	Copy(a Matrix) (r, c int)
}

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

func DenseCopyOf(a Matrix) *Dense

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

func NewDense

func NewDense(r, c int, data []float64) *Dense

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

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

func (*Dense) Add

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

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

func (*Dense) Apply

func (m *Dense) Apply(fn func(i, j int, v float64) float64, a Matrix)

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) At

func (m *Dense) At(i, j int) float64

At returns the element at row i, column j.

func (*Dense) Augment

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

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) Caps

func (m *Dense) Caps() (r, c int)

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

func (*Dense) Clone

func (m *Dense) Clone(a Matrix)

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

See the Cloner interface for more information.

func (*Dense) ColView

func (m *Dense) ColView(j int) *Vector

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

See ColViewer for more information.

func (*Dense) Copy

func (m *Dense) Copy(a Matrix) (r, c int)

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

See the Copier interface for more information.

func (*Dense) Dims

func (m *Dense) Dims() (r, c int)

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

func (*Dense) DivElem

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

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

func (*Dense) EigenvectorsSym

func (m *Dense) EigenvectorsSym(e *EigenSym)

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

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

func (*Dense) Exp

func (m *Dense) Exp(a Matrix)

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

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

func (*Dense) Grow

func (m *Dense) Grow(r, c int) Matrix

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

func (m *Dense) Inverse(a Matrix) error

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.

func (*Dense) LFromLQ

func (m *Dense) LFromLQ(lq *LQ)

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

func (Dense) MarshalBinary

func (m Dense) MarshalBinary() ([]byte, error)

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

Dense is little-endian encoded as follows:

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

func (Dense) MarshalBinaryTo

func (m Dense) MarshalBinaryTo(w io.Writer) (int, error)

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

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

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.

func (*Dense) MulElem

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

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.

func (*Dense) Outer

func (m *Dense) Outer(alpha float64, x, y *Vector)

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

m = alpha * x * y'

In order to update an existing matrix, see RankOne.

func (*Dense) Permutation

func (m *Dense) Permutation(r int, swaps []int)

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

func (m *Dense) Pow(a Matrix, n int)

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.

func (*Dense) Product

func (m *Dense) Product(factors ...Matrix)

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) QFromGSVD

func (m *Dense) QFromGSVD(gsvd *GSVD)

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

func (*Dense) QFromLQ

func (m *Dense) QFromLQ(lq *LQ)

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

func (*Dense) QFromQR

func (m *Dense) QFromQR(qr *QR)

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

func (*Dense) RFromQR

func (m *Dense) RFromQR(qr *QR)

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

func (*Dense) RankOne

func (m *Dense) RankOne(a Matrix, alpha float64, x, y *Vector)

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

m = a + alpha * x * y'

func (*Dense) RawMatrix

func (m *Dense) RawMatrix() blas64.General

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

func (m *Dense) RawRowView(i int) []float64

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

func (*Dense) Reset

func (m *Dense) Reset()

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

See the Reseter interface for more information.

func (*Dense) RowView

func (m *Dense) RowView(i int) *Vector

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

func (m *Dense) Scale(f float64, a Matrix)

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

See the Scaler interface for more information.

func (*Dense) Set

func (m *Dense) Set(i, j int, v float64)

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

func (*Dense) SetCol

func (m *Dense) SetCol(j int, src []float64)

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

func (m *Dense) SetRawMatrix(b blas64.General)

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

func (m *Dense) SetRow(i int, src []float64)

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) SigmaAFromGSVD

func (m *Dense) SigmaAFromGSVD(gsvd *GSVD)

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

func (*Dense) SigmaBFromGSVD

func (m *Dense) SigmaBFromGSVD(gsvd *GSVD)

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

func (*Dense) Slice

func (m *Dense) Slice(i, k, j, l int) Matrix

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

func (*Dense) Solve

func (m *Dense) Solve(a, b Matrix) error

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

The minimization problem solved depends on the input parameters:

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

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

func (*Dense) SolveCholesky

func (m *Dense) SolveCholesky(chol *Cholesky, b Matrix) error

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

func (*Dense) SolveLQ

func (m *Dense) SolveLQ(lq *LQ, trans bool, b Matrix) error

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

The minimization problem solved depends on the input parameters.

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

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

func (*Dense) SolveLU

func (m *Dense) SolveLU(lu *LU, trans bool, b Matrix) error

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

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

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

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

func (*Dense) SolveQR

func (m *Dense) SolveQR(qr *QR, trans bool, b Matrix) error

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

The minimization problem solved depends on the input parameters.

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

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

func (*Dense) Stack

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

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

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

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.

func (*Dense) T

func (m *Dense) T() Matrix

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

func (*Dense) UFromGSVD

func (m *Dense) UFromGSVD(gsvd *GSVD)

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

func (*Dense) UFromHOGSVD

func (m *Dense) UFromHOGSVD(gsvd *HOGSVD, n int)

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

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

func (*Dense) UFromSVD

func (m *Dense) UFromSVD(svd *SVD)

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

func (*Dense) UnmarshalBinary

func (m *Dense) UnmarshalBinary(data []byte) error

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

See MarshalBinary for the on-disk layout.

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

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

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

func (*Dense) UnmarshalBinaryFrom

func (m *Dense) UnmarshalBinaryFrom(r io.Reader) (int, error)

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

See MarshalBinary for the on-disk layout.

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

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

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

func (*Dense) VFromGSVD

func (m *Dense) VFromGSVD(gsvd *GSVD)

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

func (*Dense) VFromHOGSVD

func (m *Dense) VFromHOGSVD(gsvd *HOGSVD)

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

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

func (*Dense) VFromSVD

func (m *Dense) VFromSVD(svd *SVD)

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

func (*Dense) View

func (m *Dense) View(i, j, r, c int) Matrix

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

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

func (*Dense) ZeroRFromGSVD

func (m *Dense) ZeroRFromGSVD(gsvd *GSVD)

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

type Eigen

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

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

func (*Eigen) Factorize

func (e *Eigen) Factorize(a Matrix, left, right bool) (ok bool)

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

A right eigenvalue/eigenvector combination is defined by

A * x_r = λ * x_r

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

Similarly, a left eigenvalue/eigenvector combination is defined by

x_l * A = λ * x_l

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

Typically eigenvectors refer to right eigenvectors.

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

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

func (*Eigen) LeftVectors

func (e *Eigen) LeftVectors() *Dense

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

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

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

func (*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) Vectors

func (e *Eigen) Vectors() *Dense

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

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

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

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

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

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

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

type EigenSym

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

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

func (*EigenSym) Factorize

func (e *EigenSym) Factorize(a Symmetric, vectors bool) (ok bool)

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

A = P * D * P^-1

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

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

func (*EigenSym) Values

func (e *EigenSym) Values(dst []float64) []float64

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

Values panics if the Eigen decomposition was not successful.

type FormatOption

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"

	"github.com/gonum/matrix/mat64"
)

func main() {
	// Excerpt allows diagnostic display of very large
	// matrices and vectors.

	// The big matrix is too large to properly print...
	big := mat64.NewDense(100, 100, nil)
	for i := 0; i < 100; i++ {
		big.Set(i, i, 1)
	}

	// so only print corner excerpts of the matrix.
	fmt.Printf("excerpt big identity matrix: %v\n\n",
		mat64.Formatted(big, mat64.Prefix(" "), mat64.Excerpt(3)))

	// The long vector is also too large, ...
	long := mat64.NewVector(100, nil)
	for i := 0; i < 100; i++ {
		long.SetVec(i, float64(i))
	}

	// ... so print end excerpts of the vector,
	fmt.Printf("excerpt long column vector: %v\n\n",
		mat64.Formatted(long, mat64.Prefix(" "), mat64.Excerpt(3)))
	// or its transpose.
	fmt.Printf("excerpt long row vector: %v\n",
		mat64.Formatted(long.T(), mat64.Prefix(" "), mat64.Excerpt(3)))

}
Output:

excerpt big identity matrix: Dims(100, 100)
 ⎡1  0  0  ...  ...  0  0  0⎤
 ⎢0  1  0            0  0  0⎥
 ⎢0  0  1            0  0  0⎥
  .
  .
  .
 ⎢0  0  0            1  0  0⎥
 ⎢0  0  0            0  1  0⎥
 ⎣0  0  0  ...  ...  0  0  1⎦

excerpt long column vector: Dims(100, 1)
 ⎡ 0⎤
 ⎢ 1⎥
 ⎢ 2⎥
  .
  .
  .
 ⎢97⎥
 ⎢98⎥
 ⎣99⎦

excerpt long row vector: Dims(1, 100)
 [ 0   1   2  ...  ...  97  98  99]

func Prefix

func Prefix(p string) FormatOption

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

func Squeeze

func Squeeze() FormatOption

Squeeze sets the printing behaviour 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 mat64.GSVD
ok := gsvd.Factorize(FAO.Africa, FAO.LatinAmericaCaribbean, matrix.GSVDU|matrix.GSVDV|matrix.GSVDQ)
if !ok {
	log.Fatal("GSVD factorization failed")
}

var u, v mat64.Dense
u.UFromGSVD(&gsvd)
v.VFromGSVD(&gsvd)

s1 := gsvd.ValuesA(nil)
s2 := gsvd.ValuesB(nil)

fmt.Printf("Africa\n\ts1 = %.4f\n\n\tU = %.4f\n\n",
	s1, mat64.Formatted(&u, mat64.Prefix("\t    "), mat64.Excerpt(2)))
fmt.Printf("Latin America/Caribbean\n\ts2 = %.4f\n\n\tV = %.4f\n",
	s2, mat64.Formatted(&v, mat64.Prefix("\t    "), mat64.Excerpt(2)))

var zeroR, q mat64.Dense
zeroR.ZeroRFromGSVD(&gsvd)
q.QFromGSVD(&gsvd)
q.Mul(&zeroR, &q)
fmt.Printf("\nCommon basis vectors\n\n\tQ^T = %.4f\n",
	mat64.Formatted(q.T(), mat64.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^T = ⎡ -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

func (gsvd *GSVD) Factorize(a, b Matrix, kind matrix.GSVDKind) (ok bool)

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

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

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

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

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

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

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

func (*GSVD) GeneralizedValues

func (gsvd *GSVD) GeneralizedValues(v []float64) []float64

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

func (gsvd *GSVD) Kind() matrix.GSVDKind

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

func (*GSVD) Rank

func (gsvd *GSVD) Rank() (k, l int)

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

func (*GSVD) ValuesA

func (gsvd *GSVD) ValuesA(s []float64) []float64

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

func (gsvd *GSVD) ValuesB(s []float64) []float64

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.

type Grower

type Grower interface {
	Caps() (r, c int)
	Grow(r, c int) Matrix
}

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 mat64.HOGSVD
ok := gsvd.Factorize(FAO.Africa, FAO.Asia, FAO.LatinAmericaCaribbean, FAO.Oceania)
if !ok {
	log.Fatal("HOGSVD factorization failed: %v", gsvd.Err())
}

for i, n := range []string{"Africa", "Asia", "Latin America/Caribbean", "Oceania"} {
	var u mat64.Dense
	u.UFromHOGSVD(&gsvd, 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, mat64.Formatted(&u, mat64.Prefix("\t      ")))
}

var v mat64.Dense
v.VFromHOGSVD(&gsvd)
fmt.Printf("\nCommon basis vectors\n\n\tV^T = %.4f",
	mat64.Formatted(v.T(), mat64.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^T = ⎡-0.0897  -0.4460  -0.8905⎤
	      ⎢-0.4911  -0.5432  -0.6810⎥
	      ⎣ 0.0644   0.2841   0.9566⎦

func (*HOGSVD) Err

func (gsvd *HOGSVD) Err() error

Err returns the reason for a factorization failure.

func (*HOGSVD) Factorize

func (gsvd *HOGSVD) Factorize(m ...Matrix) (ok bool)

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

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

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

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

func (*HOGSVD) Len

func (gsvd *HOGSVD) Len() int

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

func (*HOGSVD) Values

func (gsvd *HOGSVD) Values(s []float64, n int) []float64

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) Factorize

func (lq *LQ) Factorize(a Matrix)

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

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

type LU

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

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

func (*LU) Det

func (lu *LU) Det() float64

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

func (*LU) Factorize

func (lu *LU) Factorize(a Matrix)

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

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

func (*LU) LogDet

func (lu *LU) LogDet() (det float64, sign float64)

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 (*LU) Pivot

func (lu *LU) Pivot(swaps []int) []int

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.

func (*LU) RankOne

func (lu *LU) RankOne(orig *LU, alpha float64, x, y *Vector)

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

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.

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 MutableSymmetric

type MutableSymmetric interface {
	Symmetric
	SetSym(i, j int, v float64)
}

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) Factorize

func (qr *QR) Factorize(a Matrix)

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

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

type RawColViewer

type RawColViewer interface {
	RawColView(j int) []float64
}

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

type RawMatrixSetter

type RawMatrixSetter interface {
	SetRawMatrix(a blas64.General)
}

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

type RawMatrixer interface {
	RawMatrix() blas64.General
}

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

type RawRowViewer interface {
	RawRowView(i int) []float64
}

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

type RawSymmetricer

type RawSymmetricer interface {
	RawSymmetric() blas64.Symmetric
}

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

type RawTriangular

type RawTriangular interface {
	RawTriangular() blas64.Triangular
}

type RawVectorer

type RawVectorer interface {
	RawVector() blas64.Vector
}

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 the reset matrix may result in data corruption in elements outside the view.

type RowViewer

type RowViewer interface {
	RowView(i int) *Vector
}

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 (SVD) of a matrix.

func (*SVD) Cond

func (svd *SVD) Cond() float64

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

func (svd *SVD) Factorize(a Matrix, kind matrix.SVDKind) (ok bool)

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

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

A = U * Σ * V^T

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

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

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

func (*SVD) Kind

func (svd *SVD) Kind() matrix.SVDKind

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

func (*SVD) Values

func (svd *SVD) Values(s []float64) []float64

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

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

type SymDense

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

func NewSymDense(n int, data []float64) *SymDense

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

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

func (*SymDense) AddSym

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

func (*SymDense) At

func (s *SymDense) At(i, j int) float64

At returns the element at row i and column j.

func (*SymDense) CopySym

func (s *SymDense) CopySym(a Symmetric) int

func (*SymDense) Dims

func (s *SymDense) Dims() (r, c int)

func (*SymDense) FromCholesky

func (s *SymDense) FromCholesky(chol *Cholesky)

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

func (*SymDense) GrowSquare

func (s *SymDense) GrowSquare(n int) Matrix

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

func (*SymDense) InverseCholesky

func (s *SymDense) InverseCholesky(chol *Cholesky) error

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

func (*SymDense) PowPSD

func (s *SymDense) PowPSD(a Symmetric, pow float64) error

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

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

func (*SymDense) RankTwo

func (s *SymDense) RankTwo(a Symmetric, alpha float64, x, y *Vector)

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

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

func (*SymDense) RawSymmetric

func (s *SymDense) RawSymmetric() blas64.Symmetric

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 zeros the dimensions of the matrix so that it can be reused as the receiver of a dimensionally restricted operation.

See the Reseter interface for more information.

func (*SymDense) ScaleSym

func (s *SymDense) ScaleSym(f float64, a Symmetric)

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

func (*SymDense) SetRawSymmetric

func (s *SymDense) SetRawSymmetric(b blas64.Symmetric)

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

func (*SymDense) SetSym

func (s *SymDense) SetSym(i, j int, v float64)

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

func (*SymDense) SliceSquare

func (s *SymDense) SliceSquare(i, k int) Matrix

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

func (*SymDense) SubsetSym

func (s *SymDense) SubsetSym(a Symmetric, set []int)

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"

	"github.com/gonum/matrix/mat64"
)

func main() {
	n := 5
	s := mat64.NewSymDense(5, nil)
	count := 1.0
	for i := 0; i < n; i++ {
		for j := i; j < n; j++ {
			s.SetSym(i, j, count)
			count++
		}
	}
	fmt.Println("Original matrix:")
	fmt.Printf("%0.4v\n\n", mat64.Formatted(s))

	// Take the subset {0, 2, 4}
	var sub mat64.SymDense
	sub.SubsetSym(s, []int{0, 2, 4})
	fmt.Println("Subset {0, 2, 4}")
	fmt.Printf("%0.4v\n\n", mat64.Formatted(&sub))

	// Take the subset {0, 0, 4}
	sub.SubsetSym(s, []int{0, 0, 4})
	fmt.Println("Subset {0, 0, 4}")
	fmt.Printf("%0.4v\n\n", mat64.Formatted(&sub))

}
Output:

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

Subset {0, 2, 4}
⎡ 1   3   5⎤
⎢ 3  10  12⎥
⎣ 5  12  15⎦

Subset {0, 0, 4}
⎡ 1   1   5⎤
⎢ 1   1   5⎥
⎣ 5   5  15⎦

func (*SymDense) SymOuterK

func (s *SymDense) SymOuterK(alpha float64, x Matrix)

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

func (s *SymDense) SymRankK(a Symmetric, alpha float64, x Matrix)

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

func (s *SymDense) SymRankOne(a Symmetric, alpha float64, x *Vector)

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

s = a + alpha * x * x'

func (*SymDense) Symmetric

func (s *SymDense) Symmetric() int

func (*SymDense) T

func (s *SymDense) T() Matrix

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

func (*SymDense) ViewSquare

func (s *SymDense) ViewSquare(i, n int) Matrix

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

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

type Symmetric

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 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

func (t Transpose) 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 Matrix field.

func (Transpose) Dims

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

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) T

func (t Transpose) T() Matrix

T performs an implicit transpose by returning the Matrix field.

func (Transpose) Untranspose

func (t Transpose) Untranspose() Matrix

Untranspose returns the Matrix 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, matrix.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 TriDense

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

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

func NewTriDense

func NewTriDense(n int, kind matrix.TriKind, data []float64) *TriDense

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

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

func (*TriDense) At

func (t *TriDense) At(i, j int) float64

At returns the element at row i, column j.

func (*TriDense) Copy

func (t *TriDense) Copy(a Matrix) (r, c int)

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) Dims

func (t *TriDense) Dims() (r, c int)

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) LFromCholesky

func (t *TriDense) LFromCholesky(chol *Cholesky)

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

A = L * L^T.

func (*TriDense) LFromLU

func (t *TriDense) LFromLU(lu *LU)

LFromLU extracts the lower triangular matrix from an LU factorization.

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 zeros the dimensions of the matrix so that it can be reused as the receiver of a dimensionally restricted operation.

See the Reseter interface for more information.

func (*TriDense) SetTri

func (t *TriDense) SetTri(i, j int, v float64)

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) T

func (t *TriDense) T() Matrix

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

func (*TriDense) TTri

func (t *TriDense) TTri() Triangular

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

func (*TriDense) Triangle

func (t *TriDense) Triangle() (n int, kind matrix.TriKind)

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

func (*TriDense) UFromCholesky

func (t *TriDense) UFromCholesky(chol *Cholesky)

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

A = U^T * U.

func (*TriDense) UFromLU

func (t *TriDense) UFromLU(lu *LU)

UFromLU extracts the upper triangular matrix from an LU factorization.

type Triangular

type Triangular interface {
	Matrix
	// Triangular returns the number of rows/columns in the matrix and its
	// orientation.
	Triangle() (n int, kind matrix.TriKind)

	// TTri is the equivalent of the T() method in the Matrix interface but
	// guarantees the transpose is of triangular type.
	TTri() Triangular
}

type UntransposeTrier

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 Vector

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

Vector represents a column vector.

func NewVector

func NewVector(n int, data []float64) *Vector

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

func (*Vector) AddScaledVec

func (v *Vector) AddScaledVec(a *Vector, alpha float64, b *Vector)

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

func (*Vector) AddVec

func (v *Vector) AddVec(a, b *Vector)

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

func (*Vector) At

func (v *Vector) At(i, j int) float64

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

func (*Vector) CloneVec

func (v *Vector) CloneVec(a *Vector)

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

func (*Vector) CopyVec

func (v *Vector) CopyVec(a *Vector) int

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 (*Vector) Dims

func (v *Vector) Dims() (r, c int)

func (*Vector) DivElemVec

func (v *Vector) DivElemVec(a, b *Vector)

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

func (*Vector) Len

func (v *Vector) Len() int

Len returns the length of the vector.

func (Vector) MarshalBinary

func (v Vector) MarshalBinary() ([]byte, error)

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

Vector is little-endian encoded as follows:

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

func (Vector) MarshalBinaryTo

func (v Vector) MarshalBinaryTo(w io.Writer) (int, error)

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 (*Vector) MulElemVec

func (v *Vector) MulElemVec(a, b *Vector)

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

func (*Vector) MulVec

func (v *Vector) MulVec(a Matrix, b *Vector)

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.

func (*Vector) RawVector

func (v *Vector) RawVector() blas64.Vector

func (*Vector) Reset

func (v *Vector) Reset()

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

See the Reseter interface for more information.

func (*Vector) ScaleVec

func (v *Vector) ScaleVec(alpha float64, a *Vector)

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

func (*Vector) SetVec

func (v *Vector) SetVec(i int, val float64)

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

func (*Vector) SliceVec

func (v *Vector) SliceVec(i, k int) *Vector

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

func (*Vector) SolveCholeskyVec

func (v *Vector) SolveCholeskyVec(chol *Cholesky, b *Vector) error

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

func (*Vector) SolveLQVec

func (v *Vector) SolveLQVec(lq *LQ, trans bool, b *Vector) error

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

func (*Vector) SolveLUVec

func (v *Vector) SolveLUVec(lu *LU, trans bool, b *Vector) error

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

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

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

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

func (*Vector) SolveQRVec

func (v *Vector) SolveQRVec(qr *QR, trans bool, b *Vector) error

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

func (*Vector) SolveVec

func (v *Vector) SolveVec(a Matrix, b *Vector) error

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

func (*Vector) SubVec

func (v *Vector) SubVec(a, b *Vector)

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

func (*Vector) T

func (v *Vector) T() Matrix

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

func (*Vector) UnmarshalBinary

func (v *Vector) UnmarshalBinary(data []byte) error

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

See MarshalBinary for the on-disk layout.

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

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

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

func (*Vector) UnmarshalBinaryFrom

func (v *Vector) UnmarshalBinaryFrom(r io.Reader) (int, error)

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

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

func (*Vector) ViewVec

func (v *Vector) ViewVec(i, n int) *Vector

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

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

type Viewer

type Viewer interface {
	View(i, j, r, c int) Matrix
}

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

Notes

Bugs

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL