Created
December 29, 2021 14:49
-
-
Save zetaraku/347b5900848f371a5d4ae40e51117c69 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// elementary row operations | |
function interchange(A: number[][], i1: number, i2: number) { | |
[A[i1], A[i2]] = [A[i2], A[i1]]; | |
} | |
function scaling(A: number[][], i: number, f: number = 1) { | |
const n = A[0].length; | |
for (let j = 0; j < n; j++) { | |
A[i][j] *= f; | |
} | |
} | |
function rowAddition(A: number[][], si: number, di: number, f: number = 1) { | |
const n = A[0].length; | |
for (let j = 0; j < n; j++) { | |
A[di][j] += f * A[si][j]; | |
} | |
} | |
// transforms A into reduced row echelon form | |
function rref(A: number[][]) { | |
const m = A.length; | |
const n = A[0].length; | |
// forward pass | |
for (let pi = 0, pj = 0; pi < m && pj < n; undefined) { | |
if (A[pi][pj] === 0) { | |
let ti = A.findIndex((row, i) => i > pi && row[pj] !== 0); | |
if (ti === -1) { | |
pj++; | |
continue; | |
} | |
interchange(A, pi, ti); | |
} | |
scaling(A, pi, 1 / A[pi][pj]); | |
for (let i = pi + 1; i < m; i++) { | |
rowAddition(A, pi, i, -A[i][pj]); | |
} | |
pi++, pj++; | |
} | |
// backward pass | |
for (let pi = m - 1; pi >= 0; pi--) { | |
let pj = A[pi].findIndex((col) => col !== 0); | |
if (pj === -1) { | |
continue; | |
} | |
for (let i = pi - 1; i >= 0; i--) { | |
rowAddition(A, pi, i, -A[i][pj]); | |
} | |
} | |
} | |
let A = [ | |
[1, 2, -1, 2, 1, 2], | |
[-1, -2, 1, 2, 3, 6], | |
[2, 4, -3, 2, 0, 3], | |
[-3, -6, 2, 0, 3, 9], | |
]; | |
rref(A); | |
console.log(A); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment