Skip to content

Commit

Permalink
feat: add echelonForm method
Browse files Browse the repository at this point in the history
  • Loading branch information
Goneiross authored and targos committed Jun 22, 2019
1 parent 8258497 commit eac0588
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/__tests__/matrix/utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -286,19 +286,25 @@ describe('utility methods', () => {
});

it('isEchelonForm', () => {
var matrix = new Matrix([[1, 0], [0, 1]]);
var matrix2 = new Matrix([[2, 1], [1, 1]]);
const matrix = new Matrix([[1, 0], [0, 1]]);
const matrix2 = new Matrix([[2, 1], [1, 1]]);
expect(matrix.isEchelonForm()).toStrictEqual(true);
expect(matrix2.isEchelonForm()).toStrictEqual(false);
});

it('isReducedEchelonForm', () => {
var matrix = new Matrix([[1, 0], [0, 1]]);
var matrix2 = new Matrix([[1, 1], [0, 1]]);
const matrix = new Matrix([[1, 0], [0, 1]]);
const matrix2 = new Matrix([[1, 1], [0, 1]]);
expect(matrix.isReducedEchelonForm()).toStrictEqual(true);
expect(matrix2.isReducedEchelonForm()).toStrictEqual(false);
});

it('echelonForm', () => {
const matrix = new Matrix([[1, 3], [4, 8]]);
const result = [[1, 2], [0, 1]];
expect(matrix.echelonForm().to2DArray()).toStrictEqual(result);
});

it('isRowVector', () => {
var m = new Matrix(1, 3);
expect(m.isRowVector()).toBe(true);
Expand Down
36 changes: 36 additions & 0 deletions src/matrix.js
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,42 @@ export class AbstractMatrix {
return isReducedEchelonForm;
}

/**
* @return the row echelon form of a matrix, using Gaussian elimination
*/
echelonForm() {
let result = this.clone();
let h = 0;
let k = 0;
while ((h < result.rows) && (k < result.columns)) {
let iMax = h;
for (let i = h; i < result.rows; i++) {
if (result.get(i, k) > result.get(iMax, k)) {
iMax = i;
}
}
if (result.get(iMax, k) === 0) {
k++;
} else {
result.swapRows(h, iMax);
let tmp = result.get(h, k);
for (let j = k; j < result.columns; j++) {
result.set(h, j, result.get(h, j) / tmp);
}
for (let i = h + 1; i < result.rows; i++) {
let factor = result.get(i, k) / result.get(h, k);
result.set(i, k, 0);
for (let j = k + 1; j < result.columns; j++) {
result.set(i, j, result.get(i, j) - result.get(h, j) * factor);
}
}
h++;
k++;
}
}
return result;
}

/**
* Sets a given element of the matrix.
* @abstract
Expand Down

0 comments on commit eac0588

Please sign in to comment.