Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

ml-matrix

mljs1.2mMIT6.12.0TypeScript support: included

Matrix manipulation and computation library

matrix, decomposition, SVD, singular, value, EVD, eigenvalue, LU, Qr, Cholesky, data, mining, datamining, machine, learning

readme

ml-matrix

Matrix manipulation and computation library.

Zakodium logo

Maintained by Zakodium

NPM version build status DOI npm download

Installation

$ npm install ml-matrix

Usage

As an ES module

import { Matrix } from 'ml-matrix';

const matrix = Matrix.ones(5, 5);

As a CommonJS module

const { Matrix } = require('ml-matrix');

const matrix = Matrix.ones(5, 5);

API Documentation

Examples

Standard operations

const { Matrix } = require('ml-matrix');

var A = new Matrix([
  [1, 1],
  [2, 2],
]);

var B = new Matrix([
  [3, 3],
  [1, 1],
]);

var C = new Matrix([
  [3, 3],
  [1, 1],
]);

Operations

const addition       = Matrix.add(A, B);   // addition       = Matrix [[4, 4], [3, 3], rows: 2, columns: 2]
const subtraction    = Matrix.sub(A, B);   // subtraction    = Matrix [[-2, -2], [1, 1], rows: 2, columns: 2]
const multiplication = A.mmul(B);          // multiplication = Matrix [[4, 4], [8, 8], rows: 2, columns: 2]
const mulByNumber    = Matrix.mul(A, 10);  // mulByNumber    = Matrix [[10, 10], [20, 20], rows: 2, columns: 2]
const divByNumber    = Matrix.div(A, 10);  // divByNumber    = Matrix [[0.1, 0.1], [0.2, 0.2], rows: 2, columns: 2]
const modulo         = Matrix.mod(B, 2);   // modulo         = Matrix [[1, 1], [1, 1], rows: 2, columns: 2]
const maxMatrix      = Matrix.max(A, B);   // max            = Matrix [[3, 3], [2, 2], rows: 2, columns: 2]
const minMatrix      = Matrix.min(A, B);   // max            = Matrix [[1, 1], [1, 1], rows: 2, columns: 2]

Inplace Operations

C.add(A);   // => C = C + A
C.sub(A);   // => C = C - A
C.mul(10);  // => C = 10 * C
C.div(10);  // => C = C / 10
C.mod(2);   // => C = C % 2

Math Operations

// Standard Math operations: (abs, cos, round, etc.)
var A = new Matrix([
  [ 1,  1],
  [-1, -1],
]);

var exponential = Matrix.exp(A);  // exponential = Matrix [[Math.exp(1), Math.exp(1)], [Math.exp(-1), Math.exp(-1)], rows: 2, columns: 2].
var cosinus     = Matrix.cos(A);  // cosinus     = Matrix [[Math.cos(1), Math.cos(1)], [Math.cos(-1), Math.cos(-1)], rows: 2, columns: 2].
var absolute    = Matrix.abs(A);  // absolute    = Matrix [[1, 1], [1, 1], rows: 2, columns: 2].
// Note: you can do it inplace too as A.abs()

Available Methods:

abs, acos, acosh, asin, asinh, atan, atanh, cbrt, ceil, clz32, cos, cosh, exp, expm1, floor, fround, log, log1p, log10, log2, round, sign, sin, sinh, sqrt, tan, tanh, trunc

Manipulation of the matrix

// remember: A = Matrix [[1, 1], [-1, -1], rows: 2, columns: 2]

var numberRows     = A.rows;             // A has 2 rows
var numberCols     = A.columns;          // A has 2 columns
var firstValue     = A.get(0, 0);        // get(rows, columns)
var numberElements = A.size;             // 2 * 2 = 4 elements
var isRow          = A.isRowVector();    // false because A has more than 1 row
var isColumn       = A.isColumnVector(); // false because A has more than 1 column
var isSquare       = A.isSquare();       // true, because A is 2 * 2 matrix
var isSym          = A.isSymmetric();    // false, because A is not symmetric
A.set(1, 0, 10);                         // A = Matrix [[1, 1], [10, -1], rows: 2, columns: 2]. We have changed the second row and the first column
var diag           = A.diag();           // diag = [1, -1] (values in the diagonal)
var m              = A.mean();           // m = 2.75
var product        = A.prod();           // product = -10 (product of all values of the matrix)
var norm           = A.norm();           // norm = 10.14889156509222 (Frobenius norm of the matrix)
var transpose      = A.transpose();      // transpose = Matrix [[1, 10], [1, -1], rows: 2, columns: 2]

Instantiation of matrix

var z = Matrix.zeros(3, 2); // z = Matrix [[0, 0], [0, 0], [0, 0], rows: 3, columns: 2]
var z = Matrix.ones(2, 3);  // z = Matrix [[1, 1, 1], [1, 1, 1], rows: 2, columns: 3]
var z = Matrix.eye(3, 4);   // z = Matrix [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], rows: 3, columns: 4]. there are 1 only in the diagonal

Maths

const {
  Matrix,
  inverse,
  solve,
  linearDependencies,
  QrDecomposition,
  LuDecomposition,
  CholeskyDecomposition,
  EigenvalueDecomposition,
} = require('ml-matrix');

Inverse and Pseudo-inverse

var A = new Matrix([
  [2, 3, 5],
  [4, 1, 6],
  [1, 3, 0],
]);

var inverseA = inverse(A);
var B = A.mmul(inverseA); // B = A * inverse(A), so B ~= Identity


// if A is singular, you can use SVD :
var A = new Matrix([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
]); 
// A is singular, so the standard computation of inverse won't work (you can test if you don't trust me^^)

var inverseA = inverse(A, (useSVD = true)); // inverseA is only an approximation of the inverse, by using the Singular Values Decomposition
var B = A.mmul(inverseA); // B = A * inverse(A), but inverse(A) is only an approximation, so B doesn't really be identity.
// if you want the pseudo-inverse of a matrix :
var A = new Matrix([
  [1, 2],
  [3, 4],
  [5, 6],
]);

var pseudoInverseA = A.pseudoInverse();
var B = A.mmul(pseudoInverseA).mmul(A); // with pseudo inverse, A*pseudo-inverse(A)*A ~= A. It's the case here

Least square

Least square is the following problem: We search for x, such that A.x = B (A, x and B are matrix or vectors). Below, how to solve least square with our function

// If A is non singular :
var A = new Matrix([
  [3,    1],
  [4.25, 1],
  [5.5,  1],
  [8,    1],
]);

var B = Matrix.columnVector([4.5, 4.25, 5.5, 5.5]);
var x = solve(A, B);
var error = Matrix.sub(B, A.mmul(x)); // The error enables to evaluate the solution x found.
// If A is non singular :
var A = new Matrix([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
]);

var B = Matrix.columnVector([8, 20, 32]);
var x = solve(A, B, (useSVD = true)); // there are many solutions. x can be [1, 2, 1].transpose(), or [1.33, 1.33, 1.33].transpose(), etc.
var error = Matrix.sub(B, A.mmul(x)); // The error enables to evaluate the solution x found.

Decompositions

QR Decomposition
var A = new Matrix([
  [2, 3, 5],
  [4, 1, 6],
  [1, 3, 0],
]);

var QR = new QrDecomposition(A);
var Q = QR.orthogonalMatrix;
var R = QR.upperTriangularMatrix;
// So you have the QR decomposition. If you multiply Q by R, you'll see that A = Q.R, with Q orthogonal and R upper triangular
LU Decomposition
var A = new Matrix([
  [2, 3, 5],
  [4, 1, 6],
  [1, 3, 0],
]);

var LU = new LuDecomposition(A);
var L = LU.lowerTriangularMatrix;
var U = LU.upperTriangularMatrix;
var P = LU.pivotPermutationVector;
// So you have the LU decomposition. P includes the permutation of the matrix. Here P = [1, 2, 0], i.e the first row of LU is the second row of A, the second row of LU is the third row of A and the third row of LU is the first row of A.
Cholesky Decomposition
var A = new Matrix([
  [2, 3, 5],
  [4, 1, 6],
  [1, 3, 0],
]);

var cholesky = new CholeskyDecomposition(A);
var L = cholesky.lowerTriangularMatrix;
Eigenvalues & eigenvectors
var A = new Matrix([
  [2, 3, 5],
  [4, 1, 6],
  [1, 3, 0],
]);

var e = new EigenvalueDecomposition(A);
var real = e.realEigenvalues;
var imaginary = e.imaginaryEigenvalues;
var vectors = e.eigenvectorMatrix;

Linear dependencies

var A = new Matrix([
  [2, 0, 0, 1],
  [0, 1, 6, 0],
  [0, 3, 0, 1],
  [0, 0, 1, 0],
  [0, 1, 2, 0],
]);

var dependencies = linearDependencies(A);
// dependencies is a matrix with the dependencies of the rows. When we look row by row, we see that the first row is [0, 0, 0, 0, 0], so it means that the first row is independent, and the second row is [ 0, 0, 0, 4, 1 ], i.e the second row = 4 times the 4th row + the 5th row.

License

MIT

changelog

Changelog

6.12.0 (2024-10-15)

Features

  • add mpow to compute matrix power using exponentiation by squaring (#193) (dbfd8e4)

Bug Fixes

6.11.1 (2024-06-10)

Bug Fixes

  • DistanceMatrix: fromCompact with an empty array (637598e)

6.11.0 (2023-11-30)

Features

6.10.8 (2023-11-04)

Bug Fixes

  • make default import work in TS esModuleInterop (#176) (ac52cb0)

6.10.7 (2023-10-20)

Bug Fixes

6.10.6 (2023-10-17)

Bug Fixes

6.10.5 (2023-09-24)

Bug Fixes

Documentation

6.10.4 (2022-11-05)

Bug Fixes

  • improve inspect/toString number formatter (#157) (4ed872e)

6.10.3 (2022-11-04)

Bug Fixes

  • typings: mark get/set of AbstractMatrix as abstract (#155) (d07f5c6)

6.10.2 (2022-06-29)

Bug Fixes

6.10.1 (2022-05-31)

Bug Fixes

6.10.0 (2022-04-19)

Features

6.9.0 (2022-02-26)

Features

  • allow to pass any array in all APIs (362d8a1)

6.8.2 (2021-11-12)

Bug Fixes

  • dummy commit to republish package (9ae2abe)

6.8.1 (2021-11-04)

Bug Fixes

6.8.0 (2021-04-23)

Features

6.7.0 (2021-03-12)

Features

6.6.0 (2021-01-04)

Features

6.5.3 (2020-10-11)

Bug Fixes

  • update dependencies and move documentation to gh-pages (78e0724)

6.5.2 (2020-10-09)

Bug Fixes

Reverts

  • Revert "chore: migrate release to GitHub actions (#107)" (21ba23a), closes #107

6.5.1 (2020-07-28)

Bug Fixes

  • types: add missing removeColumn and removeRow types (8010f31)
  • types: add types for addColum and addRow (#105) (b372b80)

6.5.0 (2020-05-03)

Bug Fixes

  • do not change input matrices in correlation and covariance functions (#103) (32e3537)

Features

  • add options to toString method (67b007c)
  • add toString method (dcd5ab2)

6.4.1 (2019-09-30)

Bug Fixes

  • correctly ready elements in QR#orthogonalMatrix (2f527a3)

6.4.0 (2019-08-16)

Features

  • add CholeskyDecomposition.isPositiveDefinite method (#94) (6bb33a9)

6.3.0 (2019-08-16)

Features

6.2.0 (2019-07-20)

Features

  • add NIPALS loop for factorization (#91) (043c8b6)

6.1.2 (2019-06-29)

Bug Fixes

  • use more Float64Array in decompositions (0bd8f1b)
  • Matrix: use Float64Array to improve performance (9dfe983)
  • SVD: use Float64Array to avoid deopt (85acd13)

6.1.1 (2019-06-28)

6.1.0 (2019-06-22)

Features

  • add echelonForm method (eac0588)
  • add reducedEchelonForm method (f32a8aa)
  • add statistical operations (43fc4ef)

6.0.0 (2019-04-25)

6.0.0-6 (2019-04-25)

Bug Fixes

  • add linearDependencies to TS definitions (22c4f60)

Code Refactoring

Features

  • add a custom Node.js inspect function (cb51169)
  • rename reverse methods to split (def2977)

BREAKING CHANGES

  • The signature of a few methods changed to take an options object:
  • Matrix.rand / Matrix.random
  • Matrix.randInt
  • Matrix.prototype.repeat
  • Matrix.prototype.scaleRows
  • Matrix.prototype.scaleColumns

6.0.0-5 (2019-04-18)

Code Refactoring

  • remove configurable super class and circular dependencies (dd35ec8)

BREAKING CHANGES

    • It is no longer possible to make a Matrix class that extends a custom constructor
  • matrix.det() was moved to a standalone function: determinant(matrix)
  • matrix.pseudoInverse() was moved to a standalone function: pseudoInverse(matrix)
  • matrix.linearDependencies() was moved to a standalone function: linearDependencies(matrix)
  • Matrix views must be created using their constructors instead of Matrix methods. For example, matrix.transposeView() becomes new MatrixTransposeView(matrix)

6.0.0-4 (2019-04-18)

Features

  • implement reverseRows and reverseColumns methods (77e5ed7)

6.0.0-3 (2019-04-18)

6.0.0-2 (2019-04-18)

Features

  • make JSON.stringify always return a 2D array from any matrix (021115b)

6.0.0-1 (2019-04-18)

Code Refactoring

  • make sum by row or column return an array (dbe7c99)

Features

  • add entropy method (63b95d1)
  • add mean by dimension and product methods (6b57aae)
  • add variance and standardDeviation methods (f42f1b6)

BREAKING CHANGES

  • matrix.sum('row') and matrix.sum('column') now return an array instead of a Matrix.

6.0.0-0 (2019-04-18)

chore

  • remove support for Node 6 (42e4fde)

Code Refactoring

BREAKING CHANGES

  • Node.js 6 is no longer supported.
    • Matrix no longer extends the Array class. It means that it is not possible to access and set values using array indices (e.g. matrix[i][j]). The only supported way is to use matrix.get() and matrix.set().
  • New matrices are now always filled with zeros instead of undefined.
  • The static Matrix.empty() function was removed.

5.3.0 (2019-03-23)

Bug Fixes

  • add isEchelonForm and isReducedEchelonForm to typings (690edd1)
  • correct matrix.d.ts file. (#86) (ebb273c)

Features

  • add isEchelonForm and isReducedEchelonForm (#84) (dee2a94)

5.2.1 (2019-01-07)

Bug Fixes

  • correct matrix.d.ts to follow TypeScript 3 (#81) (99329fd)

5.2.0 (2018-09-25)

Bug Fixes

  • complete type definitions (ca63059)

Features

5.1.1 (2018-05-11)

Bug Fixes

5.1.0 (2018-05-04)

Features

  • add linearDependencies method (88ee3df)

Performance Improvements

  • add transposeViewMul benchmark (0d24ea9)

5.0.1 (2017-07-28)

Bug Fixes

5.0.0 (2017-07-21)

Code Refactoring

  • change decompositions to classes (00c18e8)

BREAKING CHANGES

  • Now decompositions have to be created with "new".

4.0.0 (2017-07-19)

Code Refactoring

  • remove dependency on ml-array-utils (1e7119d)

Features

BREAKING CHANGES

  • The new ml-array-rescale dependency removes support for Node 4

3.0.0 (2017-04-25)

2.3.0 (2017-02-28)

Features

  • add pseudoinverse function based on SVD (3279a15)

2.2.0 (2016-12-14)

Bug Fixes

  • Matrix and Lu circular dependency (ab706b9)
  • styling issues picked up by Travis CI (f211a1f)

Features

  • det: add 2x2 and 3x3 determinants (04ae195)
  • det: add determinant based on LU decomposition (90532ef)
  • det: add determinant synonym (5395b56)
  • sum: sum by 'row' or 'column' (bf5d070)

2.1.0 (2016-10-07)

Bug Fixes

  • use Symbol.species as Matrix constructor in selection (fee325e)
  • use Symbol.species in evaluated static methods (39800f9)

Features

  • add fast multiplication algorithm (strassen) (fdc1c07)
  • add maxValue option to Matrix.randInt (e5a8541)
  • add value parameter to Matrix.eye (f52e4fd), closes #43
  • implement optimized algorithm for 2x2 and 3x3 multiplication (4055ef9)

2.0.0 (2016-08-04)

Features

  • add column view (5ff6680)
  • add flipColumn and flipRow views (55ee4a6)
  • add method subMatrixView (aa1df18)
  • add row view (a9e99f2)
  • add selection method and selection view (59aa861)
  • make use of Symbol.species to allow creating new matrices in any class (eaee5de)

1.4.0 (2016-08-03)

Features

  • add concept of abstract matrix (cbefc9b)
  • add method setSubMatrix (89b4242)
  • add method with one argument template (b66ee9f)
  • add repeat method (8b9eecb)
  • add transposeView (fb0a0c9)

BREAKING CHANGES

  • This is a non trivial change and could potentially break existing code. There is no known backward incompatibility though.

1.3.0 (2016-07-25)

Features

  • add methods scaleRows and scaleColumns (8516f83)

1.2.1 (2016-07-07)

Bug Fixes

  • do not use rest parameters (2c4502e)

1.2.0 (2016-07-07)

Features

1.1.5 (2016-05-31)

1.1.4 (2016-05-27)

1.1.3 (2016-05-27)

1.1.2 (2016-05-18)

1.1.1 (2016-05-18)

1.1.0 (2016-05-13)

1.0.4 (2015-11-21)

1.0.3 (2015-11-19)

Bug Fixes

  • random not correctly filling rectangular matrices (a79c3eb)

1.0.2 (2015-10-05)

1.0.1 (2015-09-11)

1.0.0 (2015-09-10)

1.0.0-0 (2015-09-09)

Bug Fixes

  • matrix: abs method should return the instance (cd96b4b)

Features

  • add fullname synonyms for some methods (4845a43)
  • add static min and max methods (41707af)
  • support all arithmetic operators and Math functions including static versions (521e4fe), closes #7

0.1.0 (2015-06-11)

0.0.4 (2015-06-11)

0.0.1 (2014-10-24)