addMatrixAndVector function

Tensor<Matrix> addMatrixAndVector(
  1. Tensor<Matrix> m,
  2. Tensor<Vector> v
)

Implementation

Tensor<Matrix> addMatrixAndVector(Tensor<Matrix> m, Tensor<Vector> v) {
  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] + v.value[j]);
    }
    outValue.add(row);
  }
  Tensor<Matrix> out = Tensor<Matrix>(outValue);
  out.creator = Node(
    [m, v],
    () {
      for (int i = 0; i < numRows; i++) {
        for (int j = 0; j < numCols; j++) {
          m.grad[i][j] += out.grad[i][j];
        }
      }
      for (int j = 0; j < numCols; j++) {
        for (int i = 0; i < numRows; i++) {
          v.grad[j] += out.grad[i][j];
        }
      }
    },
    opName: 'addMatrixAndVector', // This name is already unique
    cost: numRows * numCols,
  );
  return out;
}