/TinyMatrix

A tiny matrix library. Useful for things like tiny neural networks.

Primary LanguageJavaScriptMIT LicenseMIT

TinyMatrix

license

A tiny matrix class in JavaScript. Useful for things like tiny neural networks.

Example

var a = new Matrix([
  [ 1, 2, 3],
  [-8, 2, 4]
]);

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

var c = a.dot(b);
console.log(c.$); // [ [24, 5], [30, -4] ]
console.log(c.map(Math.abs).mean()); // 15.75

This OpenProcessing sketch uses the Matrix class to create a rudimentary neural network: https://www.openprocessing.org/sketch/386736

API

Matrix instantiation

Create a new instance of Matrix. Pass in a multidimensional array:

var m = new Matrix([
  [2, 6, 4],
  [9, 3, 1],
  [8, 2, 4]
]);

or pass a row count to create an empty matrix, or pass a row, column count to create a matrix initialized to zero.

var m = new Matrix(2,3);
console.log(m.$); // [ [0, 0, 0], [0, 0, 0] ]

Use the utility method randomize to create an array randomly initialized -1 to 1:

var m = Matrix.randomize(3,2);
console.log(m.$); // ~[ [0.4820, -0.2079], [-0.5767, 0.2396], [0.5877, -0.1864] ]

Matrix properties

Access array values using the .$ property: m.$[0][1], with 0 corresponding to the row number and 1 corresponding to the column number. Access row size and column size using .row and .col getters.

Matrix methods

Methods are non-destructive (returning a new matrix) and chainable.

.add()

a.add(b);

.sub()

a.sub(b);

.dot()

a.dot(b);  // matrix product

.mul()

a.mul(b);  // entrywise product

.map()

a.map(f);  // apply function f to each element in matrix a

.T()

a.T();  // transpose

.mean()

a.mean();  // scalar mean (not chainable)

License

MIT