Matrix class

This commit is contained in:
Filip Znachor 2022-09-29 19:14:19 +02:00
commit 1e5f2aaf6b

97
matrix.ts Normal file
View file

@ -0,0 +1,97 @@
type RawMatrix = number[][];
class Matrix {
rows: number;
cols: number;
matrix: RawMatrix;
static zero(rows: number, cols: number) {
let matrix: RawMatrix = [];
for(let i=0; i<rows; i++) {
matrix.push([]);
for(let j=0; j<cols; j++) {
matrix[i].push(0);
}
}
return new Matrix(...matrix);
}
constructor(...matrix: RawMatrix) {
this.matrix = matrix;
this.rows = matrix.length;
if(matrix.length == 0) throw Error("Empty matrix");
this.cols = matrix[0].length;
for(let i=0; i<matrix.length; i++) {
if(matrix[i].length !== this.cols) throw Error("Invalid matrix row " + (i+1));
}
}
add(other_matrix: Matrix) {
if(!(other_matrix.cols == this.cols && other_matrix.rows == this.cols)) throw Error("Other matrix has more or few rows or columns");
for(let i=0; i<this.matrix.length; i++) {
for(let j=0; j<this.matrix[i].length; j++) {
this.matrix[i][j] += other_matrix.matrix[i][j];
}
}
return this;
}
sub(other_matrix: Matrix) {
if(!(other_matrix.cols == this.cols && other_matrix.rows == this.cols)) throw Error("Other matrix has more or few rows or columns");
for(let i=0; i<this.matrix.length; i++) {
for(let j=0; j<this.matrix[i].length; j++) {
this.matrix[i][j] -= other_matrix.matrix[i][j];
}
}
return this;
}
mul(other: Matrix | number) {
if(other instanceof Matrix) {
if(!(this.cols == other.rows)) throw Error("These matrices cannot be multiplied");
let final_matrix: RawMatrix = [];
for(let a_row_i=0; a_row_i<this.matrix.length; a_row_i++) {
final_matrix.push([]);
for(let b_col_i=0; b_col_i<other.matrix[0].length; b_col_i++) {
let sum = 0;
for(let a_col_b_row_i=0; a_col_b_row_i<this.matrix[0].length; a_col_b_row_i++) {
sum += this.matrix[a_row_i][a_col_b_row_i] * other.matrix[a_col_b_row_i][b_col_i];
}
final_matrix[a_row_i].push(sum);
}
}
return new Matrix(...final_matrix);
} else {
for(let i=0; i<this.matrix.length; i++) {
for(let j=0; j<this.matrix[i].length; j++) {
this.matrix[i][j] = this.matrix[i][j] * other;
}
}
return this;
}
}
pow(power: number) {
for(let i=0; i<(power-1); i++)
this.matrix = 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<this.rows; i++) {
for(let j=0; j<this.cols; j++) {
new_matrix.matrix[j][i] = this.matrix[i][j];
}
}
return new_matrix;
}
}