Converts subscripts to linear indices.
$ npm install compute-sub2ind
For use in the browser, use browserify.
var sub2ind = require( 'compute-sub2ind' );
Converts subscripts to linear indices.
var matrix = require( 'dstructs-matrix' );
var mat = matrix( [3,2] );
/*
Matrix Subscripts Indices
[ 0 0 [ a00 a01 [ 0 1
A = 0 0 => a10 a11 => 2 3
0 0 ] a20 a21 ] 4 5 ]
*/
var idx = sub2ind( mat, 0, 0 );
// returns 0
idx = sub2ind( mat, 0, 1 );
// returns 1
idx = sub2ind( mat, 1, 0 );
// returns 2
idx = sub2ind( mat, 1, 1 );
// returns 3
idx = sub2ind( mat, 2, 0 );
// returns 4
idx = sub2ind( mat, 2, 1 );
// returns 5
-
If provided subscripts which exceed the dimensions of the input data structure, the function returns
null
.idx = sub2ind( mat, 53, 22 ); // returns null
-
Matrices are views on top of typed arrays. While the relation between subscripts, indices, and the underlying storage appears straightforward in the example above, this may not necessarily hold true for matrices which have been reshaped (e.g., fliplr, flipud, transpose, etc).
var fliplr = require( 'compute-fliplr' ); var data = new Int8Array( 6 ); for ( var i = 0; i < data.length; i++ ) { data[ i ] = i*10; } var mat = matrix( data, [3,2], 'int8' ); /* Matrix Subscripts Indices Storage [ 0 10 [ a00 a01 [ 0 1 [ 0 1 A = 20 30 => a10 a11 => 2 3 => 2 3 40 50 ] a20 a21 ] 4 5 ] 4 5 ] */ var lr = fliplr( mat ); /* Matrix Subscripts Indices Storage [ 10 0 [ a00 a01 [ 0 1 [ 1 0 B = 30 20 => a10 a11 => 2 3 => 3 2 50 40 ] a20 a21 ] 4 5 ] 5 4 ] */
var matrix = require( 'dstructs-matrix' ),
sub2ind = require( 'compute-sub2ind' );
var data,
mat,
idx,
k, i, j;
data = new Int8Array( 10000 );
mat = matrix( data, [100,100], 'int8' );
idx = new Array( 100 );
for ( k = 0; k < idx.length; k++ ) {
i = Math.round( Math.random()*99 );
j = Math.round( Math.random()*99 );
idx[ k ] = sub2ind( mat, i, j );
}
console.log( idx.join( '\n' ) );
To run the example code from the top-level application directory,
$ node ./examples/index.js
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.
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
Copyright © 2015. The Compute.io Authors.