addScalarToMatrix function

Tensor<Matrix> addScalarToMatrix(
  1. Tensor<Matrix> m,
  2. Tensor<Scalar> s
)

Implementation

Tensor<Matrix> addScalarToMatrix(Tensor<Matrix> m, Tensor<Scalar> s) {
  int numRows = m.value.length;
  int numCols = m.value[0].length;
  Matrix outValue = [];
  for (int i = 0; i < numRows; i++) {
    Vector row = [];
    for (int j = 0; j < numCols; j++) {
      row.add(m.value[i][j] + s.value);
    }
    outValue.add(row);
  }
  Tensor<Matrix> out = Tensor<Matrix>(outValue);
  out.creator = Node(
    [m, s],
    () {
      for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numCols; j++) {
          m.grad[i][j] += out.grad[i][j];
        }
      }
      s.grad += sumMatrix(Tensor<Matrix>(out.grad)).value;
    },
    opName: 'addScalarToMatrix', // This name is already unique
    cost: numRows * numCols,
  );
  return out;
}