An experimental library for matrix manipulation implemented in Golang.
- Portability - Implement in pure Golang to achieve cgo-free.
- Efficiency - Pursue performance as possible without highly optimized back-ends like blas.
- Simplicity - Provide clean API.
For installation, execute the following command:
$ go get github.com/mitsuse/matrix-go
Currently, the following types are implemented:
- mutable dense matrix
Use dense.New
to create a new dense matrix with given elements.
// Create a 2 x 3 matrix.
m := dense.New(2, 3)(
0, 1, 2,
3, 4, 5,
)
To create zero matrix, call dense.Zeros
instead.
// Create a 2 x 3 zero matrix.
m := dense.Zeros(2, 3)
Add a matrix to other with (Matrix).Add
:
m := dense.New(2, 3)(
0, 1, 2,
3, 4, 5,
)
n := dense.New(2, 3)(
5, 4, 3,
2, 1, 0,
)
r := dense.New(2, 3)(
5, 5, 5,
5, 5, 5,
)
// true
m.Add(n).Equal(r)
Similarly, (Matrix).Subtract
is used for subtraction on two matrix.
When the receiver is mutable,
(Matrix).Add
and (Matrix).Subtract
return the receiver itself,
the elements of which is rewritten.
The product of two matrices can be calculated by (Matrix).Multiply
.
m := dense.New(3, 2)(
0, 1,
2, 3,
4, 5,
)
n := dense.New(2, 1)(
0,
-1,
)
r := dense.New(3, 1)(
-1,
-3,
-5,
)
m.Multiply(n).Equal(r)
Matrix multiplication always create a new matrix. The type of the result matrix is same as the type of the receiver.
(Matrix).Scalar
is available for Scalar multiplication (scalar-left multiplication).
m := dense.New(2, 2)(
0, 1,
2, 3,
)
r := dense.New(2, 2)(
0, -1,
-2, -3,
)
// true
m.Scalar(-1).Equal(r)
For scalar-right multiplication, use (Scalar).Multiply
.
m := dense.New(2, 2)(
0, 1,
2, 3,
)
r := dense.New(2, 2)(
0, -1,
-2, -3,
)
// true
Scalar(-1).Multiply(m).Equal(r)
When the matrix used for scalar multiplication is mutable,
(Matrix).Scalar
and (Scalar).Multiply
rewrite elements of the matrix.
Matrix
has several methods to iterate elements.
They return a value typed as Cursor
which is a reference to the element to visit.
m := dense.New(2, 3)(
0, 1, 2,
3, 4, 5,
)
// Create a cursor to iterate all elements of matrix m.
c := m.All()
// Check whether the element to visit exists or not.
for c.HasNext() {
element, row, column := c.Get()
fmt.Printf(
"element = %d, row = %d, column = %d\n",
element,
row,
column,
)
}
Currently, three methods are implemented which return a cursor:
(Matrix).All
(Matrix).NonZeros
(Matrix).Diagonal
For details, please read the documentation of
types.Matrix
.
Maxtrix
provides methods to find the maximum or minimum elements.
(Matrix).Max
returns the one of maximum elements and its index (the row and column).
(Matrix).Min
also does similarly.
m := dense.New(3, 3)(
0, 1, 2,
3, 4, 5,
4, 3, 2,
)
// Find the one of maximum elements.
element, row, column := m.Max()
// true
element == 5
// true
row == 1
// true
column == 2
Please read the documentation.
This is a list of projects using mitsuse/matrix-go
.
- Olive - Online algorithms for machine learning implemented in Golang.
Please read LICENSE.txt.