/to-matrix

Construct a matrix from an array of arrays.

Primary LanguageJavaScriptMIT LicenseMIT

to-matrix

NPM version Build Status Coverage Status Dependencies

Construct a matrix from an array of arrays.

Installation

$ npm install compute-to-matrix

For use in the browser, use browserify.

Usage

var toMatrix = require( 'compute-to-matrix' );

toMatrix( arr[, options ] )

Constructs a matrix from an array of arrays.

var arr = [
	[ 1, 2, 3 ],
	[ 4, 5, 6 ],
	[ 7, 8, 9 ]
]

var mat = toMatrix( arr );
/*
	[ 1 2 3
	  4 5 6
	  7 8 9 ]
*/

The function accepts the following options:

  • accessor: accessor function for accessing array values.
  • dtype: matrix data type. Default: float64.

For non-numeric nested arrays, provide an accessor function for accessing array values.

var arr = [
	[ {'x': 1}, {'x': 0}, {'x': 0} ],
	[ {'x': 0}, {'x': 1}, {'x': 0} ],
	[ {'x': 0}, {'x': 0}, {'x': 1} ],
];

function getValue( d, i, j ) {
	return d.x;
}

var mat = toMatrix( arr, {
	'accessor': getValue
});
/*
	[ 1 0 0
	  0 1 0
	  0 0 1 ]
*/

The accessor function is provided three arguments:

  • d: the current element
  • i: the row index of the current element
  • j: the column index of the current element

By default, the matrix elements are floating-point 64-bit numbers (float64). To specify a different data type, set the dtype option.

var arr = [
	[ 1.1, 2.3 ],
	[ 3.2, 4.1 ]
];

var mat = toMatrix( arr, {
	'dtype': 'int32'
});
/*
	[ 1 2
	  3 4 ]
*/

For supported data types, see dstructs-matrix.

Examples

var toMatrix = require( 'compute-to-matrix' );

var nRows,
	nCols,
	arr,
	mat,
	i, j;

arr = [
	[ 2, 4, 3, 1],
	[ 1, 2, 2, 1],
	[ 7, 3, 9, 7],
	[ 11, 9, 9, 8],
	[ 3, 2, 3, 1]
];

nRows = arr.length;
nCols = arr[ 0 ].length;

mat = toMatrix( arr );

for ( i = 0; i < nRows; i++ ) {
	for ( j = 0; j < nCols; j++ ) {
		console.log( '(%d,%d) -> %d', i, j, mat.get( i, j ) );
	}
}

To run the example code from the top-level application directory,

$ node ./examples/index.js

Tests

Unit

Unit tests use the Mocha test framework with Chai assertions. To run the tests, execute the following command in the top-level application directory:

$ make test

All new feature development should have corresponding unit tests to validate correct functionality.

Test Coverage

This repository uses Istanbul as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:

$ make test-cov

Istanbul creates a ./reports/coverage directory. To access an HTML version of the report,

$ make view-cov

License

MIT license.

Copyright

Copyright © 2015. The Compute.io Authors.