Home Reference Source Repository

mathlab

Lodash like math lab in javascript, focusing on matrix manipulation.

npm

Install

Using npm:

$ npm install mathlab --save

Using cdn:

<script src="https://unpkg.com/mathlab/dist/axios.min.js"></script>

Sample usage

import { dot } from 'mathlab'

const A = [[1,2,3],
           [4,5,6]]

const x = [7,8,9]

// calculate dot product
dot(A, x) // [50,122]

Features

Introduction to functions

Mathlab provide a collection of mathmatic functions which can be applied to numbers, arrays and two self-defined datatypes (Complex and Sparse).

Functions can be devide into 5 groups:

1. Math Object functions

abs | acos | asin | atan | ceil | cos | exp | floor | log | round | sin | sqrt | tan

The Math object functions have been adapted to work on Arrays, Complex and Sparse Objects

example

import {abs, Complex, Sparse} from './mathlab'

abs(-1)  // 1
abs([-1, 2])  // [1, 2]
abs(new Complex(3, 4))  // {re: 5, im: 0}
abs(new Sparse([[1,2,0],[0,0,-1],[1,0,0]])) // {row: col: val:}

2. Arithmetic operations

add | sub | mul | div | neg

The standard arithmetic operations have been vectorized:

example

import { add, Complex } from 'mathlab'

add(1, 2) // 3
add([1,2], 2,2) // [3,4]

3. Linear algebra

dot | solve | det | inv | norm2 | tensor | eig

example: dot

dot([[1, 1], [2, 1]], [1, 2]) // [3, 4]

4. Fast Fourier Transforms

fft | ifft

example

import {fft, ifft, Complex} from 'mathlab'

// {re: [ 15, -5.941, -3.312, -1.688, 0.941], im: [ 40, 0.941, -1.688, -3.312, -5.941]}
const fftRes = fft(new Complex([1,2,3,4,5],[6,7,8,9,10]))

// {re:[1,2,3,4,5], im:[6,7,8,9,10]}
ifft(fftRes)

5. Utility functions

dim | same | rep | diag | identity | random | linspace

example dim

dim(1) // []
dim([1,2]) // [2]
dim([[1,2],[2,2],[3,3]]) // [3,2]

Introduction to Complex and Sparse matrix

Mathlab provided two Classes for you to initialize Complex and Sparse matrix.

Complex

Creates a Complex instance that represents a complex number or array. It accepts two arguments as the real and imaginary part of a complex number or array.

Usage

Initalize

import { Complex, abs } from 'mathlab'

// complex number
const c = new Complex(1, 2) // {re:1, im:2}

// complex array
const ca = new Complex([1,2], [1,2]) // {re:[1,2], im:[1,2]}

// mathlab functions can be applied on it
abs(ca) // {re: [ 1.414, 2.828], im: undefined}

Methods (still adding)

ca.reciprocal() // {re: [ 0.5, 0.25], im: [ -0.5, -0.25]}

Sparse

Creates a Sparse instance that represents a sparse matrix. In mathlab, sparse matrices are stored in the compressed column storage ordering.

Usage

Initialize

import { Sparse } from 'mathlab'

const z = new Sparse([[1,0,0],[5,2,0],[1,0,0]]) //  { col: [ 0, 3, 4, 4 ], row: [ 0, 1, 2, 1 ], val: [ 1, 5, 1, 2 ] }

Methods (still adding)

z.toFull() // [[1,0,0],[5,2,0],[1,0,0]]

Thanks

Mathlab start as a refactoring of numeric