js 实现矩阵
在 JavaScript 中实现矩阵操作可以通过多种方式完成,包括使用数组、自定义类或第三方库。以下是几种常见方法:
使用二维数组表示矩阵
矩阵可以直接用二维数组表示,每个子数组代表一行:
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
矩阵基本操作
访问元素
通过行列索引访问:

const element = matrix[row][col];
矩阵转置
交换行和列:
function transpose(matrix) {
return matrix[0].map((_, col) => matrix.map(row => row[col]));
}
矩阵乘法
两个矩阵相乘:

function multiply(a, b) {
const result = [];
for (let i = 0; i < a.length; i++) {
result[i] = [];
for (let j = 0; j < b[0].length; j++) {
let sum = 0;
for (let k = 0; k < a[0].length; k++) {
sum += a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
return result;
}
使用自定义类封装
可以创建一个 Matrix 类封装操作:
class Matrix {
constructor(data) {
this.data = data;
this.rows = data.length;
this.cols = data[0].length;
}
multiply(other) {
if (this.cols !== other.rows) throw new Error('维度不匹配');
const result = new Array(this.rows);
for (let i = 0; i < this.rows; i++) {
result[i] = new Array(other.cols);
for (let j = 0; j < other.cols; j++) {
let sum = 0;
for (let k = 0; k < this.cols; k++) {
sum += this.data[i][k] * other.data[k][j];
}
result[i][j] = sum;
}
}
return new Matrix(result);
}
}
使用第三方库
对于复杂操作,推荐使用专门库如 math.js:
import * as math from 'mathjs';
const matrixA = math.matrix([[1, 2], [3, 4]]);
const matrixB = math.matrix([[5, 6], [7, 8]]);
const result = math.multiply(matrixA, matrixB);
性能优化
对于大型矩阵,考虑使用 TypedArray(如 Float64Array)存储数据,或使用 WebGL/GPU 加速库(如 gpu.js)。
以上方法涵盖了从基础实现到高级应用的场景,可根据需求选择适合的方案。






