You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在两个Breeze矩阵上应用自定义函数(类似矩阵加法操作)

实现矩阵的map2方法

我们可以给矩阵类添加一个map2方法,让它能接收另一个矩阵和二元处理函数,逐元素对两个矩阵的对应位置应用函数,最终返回新的结果矩阵。

核心实现(JavaScript)

class Matrix {
  constructor(rows) {
    this.rows = rows;
    this.rowCount = rows.length;
    this.colCount = rows[0]?.length || 0;
  }

  map2(otherMatrix, fn) {
    // 校验矩阵维度一致性
    if (this.rowCount !== otherMatrix.rowCount || this.colCount !== otherMatrix.colCount) {
      throw new Error('两个矩阵的行数和列数必须一致');
    }

    // 逐元素应用自定义函数
    const resultRows = this.rows.map((row, rowIndex) => {
      return row.map((valM1, colIndex) => {
        const valM2 = otherMatrix.rows[rowIndex][colIndex];
        return fn(valM1, valM2);
      });
    });

    return new Matrix(resultRows);
  }
}

使用示例

// 初始化测试矩阵
const matrix1 = new Matrix([
  [1, 2],
  [3, 4]
]);

const matrix2 = new Matrix([
  [5, 6],
  [7, 8]
]);

// 实现矩阵加法
const sumMatrix = matrix1.map2(matrix2, (valM1, valM2) => valM1 + valM2);
console.log(sumMatrix.rows); // 输出 [[6, 8], [10, 12]]

// 实现逐元素相乘
const productMatrix = matrix1.map2(matrix2, (valM1, valM2) => valM1 * valM2);
console.log(productMatrix.rows); // 输出 [[5, 12], [21, 32]]

// 自定义逻辑:取对应位置较大值
const maxMatrix = matrix1.map2(matrix2, (valM1, valM2) => Math.max(valM1, valM2));
console.log(maxMatrix.rows); // 输出 [[5, 6], [7, 8]]

关键细节

  • 维度校验:必须确保两个矩阵的行数和列数完全一致,否则抛出错误,避免元素不匹配的问题。
  • 纯函数设计:map2方法不会修改原矩阵,而是返回新的Matrix实例,避免副作用。
  • 灵活性:传入的二元函数支持任意自定义逻辑,覆盖加减乘以外的多种场景。

内容的提问来源于stack exchange,提问作者Sven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 05:10:19