class Matrix {
constructor(data) {
this.data = data;
this.rows = data.length;
this.cols = data[0].length;
}
toString() {
return this.data.map((row) => row.join(" ")).join("\n");
}
add(other) {
if (this.rows !== other.rows || this.cols !== other.cols) {
throw new Error("Matrices must have the same dimensions for addition");
}
const result = [];
for (let i = 0; i < this.rows; i++) {
result.push([]);
for (let j = 0; j < this.cols; j++) {
result[i][j] = this.data[i][j] + other.data[i][j];
}
}
return new Matrix(result);
}
subtract(other) {
if (this.rows !== other.rows || this.cols !== other.cols) {
throw new Error("Matrices must have the same dimensions for subtraction");
}
const result = [];
for (let i = 0; i < this.rows; i++) {
result.push([]);
for (let j = 0; j < this.cols; j++) {
result[i][j] = this.data[i][j] - other.data[i][j];
}
}
return new Matrix(result);
}
multiply(scalar) {
const result = [];
for (let i = 0; i < this.rows; i++) {
result.push([]);
for (let j = 0; j < this.cols; j++) {
result[i][j] = this.data[i][j] * scalar;
}
}
return new Matrix(result);
}
divide(scalar) {
if (scalar === 0) {
throw new Error("Division by zero is not allowed");
}
const result = [];
for (let i = 0; i < this.rows; i++) {
result.push([]);
for (let j = 0; j < this.cols; j++) {
result[i][j] = this.data[i][j] / scalar;
}
}
return new Matrix(result);
}
transpose() {
const result = [];
for (let i = 0; i < this.cols; i++) {
result.push([]);
for (let j = 0; j < this.rows; j++) {
result[i][j] = this.data[j][i];
}
}
return new Matrix(result);
}
static identity(size) {
const data = Array.from({ length: size }, (_, i) =>
Array.from({ length: size }, (_, j) => (i === j ? 1 : 0))
);
return new Matrix(data);
}
static listToMatrix(lst) {
return new Matrix(lst);
}
static matrixMultiply(matrix1, matrix2) {
if (matrix1.cols !== matrix2.rows) {
throw new Error(
"Number of columns in the first matrix must be equal to the number of rows in the second matrix"
);
}
const result = [];
for (let i = 0; i < matrix1.rows; i++) {
result.push([]);
for (let j = 0; j < matrix2.cols; j++) {
let sum = 0;
for (let k = 0; k < matrix1.cols; k++) {
sum += matrix1.data[i][k] * matrix2.data[k][j];
}
result[i][j] = sum;
}
}
return new Matrix(result);
}
}