Skip to content

Commit eac0588

Browse files
Goneirosstargos
authored andcommitted
feat: add echelonForm method
1 parent 8258497 commit eac0588

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

src/__tests__/matrix/utility.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -286,19 +286,25 @@ describe('utility methods', () => {
286286
});
287287

288288
it('isEchelonForm', () => {
289-
var matrix = new Matrix([[1, 0], [0, 1]]);
290-
var matrix2 = new Matrix([[2, 1], [1, 1]]);
289+
const matrix = new Matrix([[1, 0], [0, 1]]);
290+
const matrix2 = new Matrix([[2, 1], [1, 1]]);
291291
expect(matrix.isEchelonForm()).toStrictEqual(true);
292292
expect(matrix2.isEchelonForm()).toStrictEqual(false);
293293
});
294294

295295
it('isReducedEchelonForm', () => {
296-
var matrix = new Matrix([[1, 0], [0, 1]]);
297-
var matrix2 = new Matrix([[1, 1], [0, 1]]);
296+
const matrix = new Matrix([[1, 0], [0, 1]]);
297+
const matrix2 = new Matrix([[1, 1], [0, 1]]);
298298
expect(matrix.isReducedEchelonForm()).toStrictEqual(true);
299299
expect(matrix2.isReducedEchelonForm()).toStrictEqual(false);
300300
});
301301

302+
it('echelonForm', () => {
303+
const matrix = new Matrix([[1, 3], [4, 8]]);
304+
const result = [[1, 2], [0, 1]];
305+
expect(matrix.echelonForm().to2DArray()).toStrictEqual(result);
306+
});
307+
302308
it('isRowVector', () => {
303309
var m = new Matrix(1, 3);
304310
expect(m.isRowVector()).toBe(true);

src/matrix.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,42 @@ export class AbstractMatrix {
399399
return isReducedEchelonForm;
400400
}
401401

402+
/**
403+
* @return the row echelon form of a matrix, using Gaussian elimination
404+
*/
405+
echelonForm() {
406+
let result = this.clone();
407+
let h = 0;
408+
let k = 0;
409+
while ((h < result.rows) && (k < result.columns)) {
410+
let iMax = h;
411+
for (let i = h; i < result.rows; i++) {
412+
if (result.get(i, k) > result.get(iMax, k)) {
413+
iMax = i;
414+
}
415+
}
416+
if (result.get(iMax, k) === 0) {
417+
k++;
418+
} else {
419+
result.swapRows(h, iMax);
420+
let tmp = result.get(h, k);
421+
for (let j = k; j < result.columns; j++) {
422+
result.set(h, j, result.get(h, j) / tmp);
423+
}
424+
for (let i = h + 1; i < result.rows; i++) {
425+
let factor = result.get(i, k) / result.get(h, k);
426+
result.set(i, k, 0);
427+
for (let j = k + 1; j < result.columns; j++) {
428+
result.set(i, j, result.get(i, j) - result.get(h, j) * factor);
429+
}
430+
}
431+
h++;
432+
k++;
433+
}
434+
}
435+
return result;
436+
}
437+
402438
/**
403439
* Sets a given element of the matrix.
404440
* @abstract

0 commit comments

Comments
 (0)