A library to use in the browser or node.js. It currently contains:
- Basic Matrix operations
- LU decomposition
- UD decomposition (optimized cholesky decomposition)
Browser
To use the library in the browser, you need to include this JavaScript file:
It exports the global m4th
object. Now you can access e.g. the matrix constructor with:
var M = m4thmatrix;
The following browsers are tested:
node.js
You can install this package with:
npm install m4th
Now you can load e.g. the matrix constructor with:
var M = ;
Examples
Matrix Creation
Create a 2x3 matrix (2 rows, 3 columns) and a 4x4 matrix with undefined
entries:
var A B;A = ;B = ;
Create a 2x2 matrix and a 2x3 matrix with the given content:
var A B;A = ;B = ;
Matrix Entries
Each matrix has readable rows
and columns
properties:
console;
Matrix entries can be accessed with get()
and set()
(indices start at 0
):
var a = A; // get entry in row 0 and column 3A; // set entry in row 1 and column 2 to value 3
You can chain set()
:
A;
Imperative / Functional
Calculations on matrices can be done in imperative or functional style.
For example the frobenius norm of a matrix A
can be calculated imperatively:
var i j a norm;norm = 0;for i = 0; i < Arows; i += 1 // iterate matrix rows for j = 0; j < Acolumns; j += 1 // iterate matrix columns a = A; norm += a * a; norm = Math;
But we can do better using each()
which takes a callback as an argument:
var norm = 0;A;norm = Math;
In a more functional style the same can be expressed with map()
and reduce()
:
var square add norm;// helper functions { return x * x;}; { return x + y;};// calculate normnorm = Math;
This now reads nicer than the imperative approach.
If performance is important, you can remove the map()
call (which creates a temporary matrix) and use a single
reduce()
instead:
var addSquared norm;// helper function { return x + y * y;};// calculate normnorm = Math;
Matrix Operations
// calculate some results without changing the matrices A, B and C:console;console;console;console;console;console;console;console;console;
map()
Create a 5x5 hilbert matrix:
var H = ;
LU decomposition
var A y LU x Ainv;// create some matrices:A = ; y = ; // LU decompose matrix A LU = m4th; // node.js: require('m4th/lu')(A);// calculate solution for: y = A*xx = LU;// invert matrix AAinv = LU;
UD decomposition
var A y UD x;// create some matrices:A = ; y = ; // UD decompose matrix A UD = m4th; // node.js: require('m4th/ud')(A);// calculate solution for: y = A*xx = UD;