addMatrix function
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
Implementation
// MATRIX (2D) OPERATIONS
////////////////////////////////////////////////////////////////////////////////
// Assuming your Tensor, Node, and type aliases are defined.
Tensor<Matrix> addMatrix(Tensor<Matrix> a, Tensor<Matrix> b) {
int numRows = a.value.length;
int numCols = a.value[0].length;
Matrix outValue = [];
for (int i = 0; i < numRows; i++) {
Vector row = [];
for (int j = 0; j < numCols; j++) {
row.add(a.value[i][j] + b.value[i][j]);
}
outValue.add(row);
}
Tensor<Matrix> out = Tensor<Matrix>(outValue);
out.creator = Node(
[a, b],
() {
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
a.grad[i][j] += out.grad[i][j];
b.grad[i][j] += out.grad[i][j];
}
}
},
opName: 'add_matrix', // <-- Renamed for clarity
cost: numRows * numCols,
);
return out;
}