export type RawMatrix = number[][]; export enum TriangularForm {UPPER, LOWER}; export class Matrix { rows!: number; cols!: number; matrix!: RawMatrix; static zero(rows: number, cols: number) { let matrix: RawMatrix = []; for(let i=0; i 0) for(let i=0; i<(power-1); i++) this.set(...this.mul(this).matrix); return this; } invert() { this.matrix = this.mul(-1).matrix; return this; } transpose() { let new_matrix = Matrix.zero(this.cols, this.rows); for(let i=0; i pivot_index) pivot_index = j; } else if(pivot_index >= j) return false; } pivot_index++; } return true; } is_triangular(form: TriangularForm = TriangularForm.UPPER) { for(let i=0; i { matrix.matrix[i][this.cols+i] = 1; row.forEach((col, j) => { matrix.matrix[i][j] = col; }); }); let gje = GaussianElimination.gje(matrix).matrix.map(GaussianElimination.make_pivot_1); let result = Matrix.zero(this.rows, this.cols); result.set(...result.matrix.map((row, i) => { return row.map((col, j) => gje[i][this.cols+j]); })); return result; } } export abstract class GaussianElimination { static make_pivot_1(row: number[]) { let d = 0; return row.map((n, i) => { if(n != 0 && !d) d = n; return d && n ? n / d : 0; }); } static sort(matrix: Matrix) { let m = matrix.matrix; let new_matrix = [m[0]]; let pivots = matrix.pivots(); for(let i=1; i c + n*m[v_offset][j]); } } return matrix; } static gje(matrix: Matrix): Matrix { matrix = this.ge(matrix); let pivots = matrix.pivots(); for(let v_offset=matrix.rows-1; v_offset>0; v_offset--) { let m = matrix.matrix; let h_offset = pivots[v_offset]; if(h_offset >= matrix.cols) continue; let first_number = m[v_offset][h_offset]; for(let i=v_offset-1; i>=0; i--) { let n = -m[i][h_offset]/first_number; m[i] = m[i].map((c, j) => c + n*m[v_offset][j]); } } return matrix; } static solve(matrix: Matrix): number[] | Matrix { let solved_matrix = this.gje(matrix); let pivots = solved_matrix.pivots(); let results: number[] = []; solved_matrix.matrix = solved_matrix.matrix.map(GaussianElimination.make_pivot_1); for(let row=0; row isNaN(n)).length == 0) return results; else return solved_matrix; } }