elementWiseMultiplyMatrix function

Tensor<Matrix> elementWiseMultiplyMatrix(
  1. Tensor<Matrix> a,
  2. Tensor<Matrix> b
)

Implementation

Tensor<Matrix> elementWiseMultiplyMatrix(Tensor<Matrix> a, Tensor<Matrix> b) {
  int numRows = a.shape[0];
  int numCols = a.shape[1];

  Matrix aMat = a.value;
  Matrix bMat = b.value;

  Matrix outValue = [];
  for (int i = 0; i < numRows; i = i + 1) {
    Vector row = [];
    for (int j = 0; j < numCols; j = j + 1) {
      row.add(aMat[i][j] * bMat[i][j]);
    }
    outValue.add(row);
  }

  Tensor<Matrix> out = Tensor<Matrix>(outValue);

  out.creator = Node(
    [a, b],
        () {
      int length = a.data.length;
      for (int i = 0; i < length; i = i + 1) {
        a.grad[i] = a.grad[i] + out.grad[i] * b.data[i];
        b.grad[i] = b.grad[i] + out.grad[i] * a.data[i];
      }
    },
    opName: 'multiply_matrix',
    cost: numRows * numCols,
  );
  return out;
}