Skip to content

Commit

Permalink
feat: check if is a banded matrix
Browse files Browse the repository at this point in the history
  • Loading branch information
maasencioh committed Jun 10, 2017
1 parent c264545 commit 2f5c688
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
30 changes: 28 additions & 2 deletions src/__tests__/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,33 @@ describe('Sparse Matrix', () => {
});

it('transpose', () => {
const matrix1 = new SparseMatrix([[1, 2], [3, 4]]);
expect(matrix1.transpose().to2DArray()).toEqual([[1, 3], [2, 4]]);
const matrix = new SparseMatrix([[1, 2], [3, 4]]);
expect(matrix.transpose().to2DArray()).toEqual([[1, 3], [2, 4]]);
});
});

describe('Banded matrices', () => {
it('Check band size', () => {
const matrix1 = new SparseMatrix([[1, 0], [0, 1]]);
const matrix2 = new SparseMatrix([[1, 0, 0], [0, 1, 0]]);
const matrix3 = new SparseMatrix([[1, 0, 1], [0, 1, 0]]);
const matrix4 = new SparseMatrix([[1, 0, 0], [1, 1, 0]]);
const matrix5 = new SparseMatrix([[0, 0, 0], [1, 0, 0], [0, 1, 0]]);
expect(matrix1.bandWidth()).toBe(0);
expect(matrix2.bandWidth()).toBe(0);
expect(matrix3.bandWidth()).toBe(2);
expect(matrix4.bandWidth()).toBe(1);
expect(matrix5.bandWidth()).toBe(0);
});

it('isBanded', () => {
const matrix1 = new SparseMatrix([[1, 0], [0, 1]]);
const matrix2 = new SparseMatrix([[1, 0, 0], [0, 1, 0]]);
const matrix3 = new SparseMatrix([[1, 0, 1], [0, 1, 0]]);
const matrix4 = new SparseMatrix([[1, 0, 0], [1, 1, 0]]);
expect(matrix1.isBanded(1)).toBe(true);
expect(matrix2.isBanded(1)).toBe(true);
expect(matrix3.isBanded(1)).toBe(false);
expect(matrix4.isBanded(1)).toBe(true);
});
});
26 changes: 26 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,32 @@ export class SparseMatrix {
return symmetric;
}

/**
* Search for the wither band in the main diagonals
* @return {number}
*/
bandWidth() {
let min = this.columns;
let max = -1;
this.forEachNonZero((i, j, v) => {
let diff = i - j;
min = Math.min(min, diff);
max = Math.max(max, diff);
return v;
});
return max - min;
}

/**
* Test if a matrix is consider banded using a threshold
* @param {number} width
* @return {boolean}
*/
isBanded(width) {
let bandWidth = this.bandWidth();
return bandWidth <= width;
}

get cardinality() {
return this.elements.size;
}
Expand Down

0 comments on commit 2f5c688

Please sign in to comment.