broadcast method

List<Matrix> broadcast(
  1. Matrix b
)

Broadcasts the current matrix with matrix b.

If the matrices are compatible for broadcasting, it replicates the input matrices along the required dimensions to produce two matrices with the same shape.

b The matrix to be broadcasted with the current matrix.

Returns a list of two matrices, the first one being the broadcasted version of the current matrix, and the second one being the broadcasted version of matrix b.

Example:

Matrix a = Matrix([
  [1, 2, 3],
]);

Matrix b = Matrix([
  [1],
  [2],
  [3],
]);

List<Matrix> broadcasted = a.broadcast(b);
print(broadcasted[0]);

Output:

Matrix: 3x3
┌ 1  2  3 ┐
│ 1  2  3 │
└ 1  2  3 ┘

print(broadcasted[1]);

Output:

Matrix: 3x3
┌ 1  1  1 ┐
│ 2  2  2 │
└ 3  3  3 ┘

Implementation

List<Matrix> broadcast(Matrix b) {
  // Check compatibility
  if (!isCompatibleForBroadcastWith(b)) {
    throw Exception('Matrices are not compatible for broadcasting.');
  }

  // Determine the dimensions of the output matrices
  int numRows = math.max(rowCount, b.rowCount).toInt();
  int numCols = math.max(columnCount, b.columnCount).toInt();

  // Broadcast and replicate the input matrices
  Matrix aBroadcasted = replicateMatrix(numRows, numCols);
  Matrix bBroadcasted = b.replicateMatrix(numRows, numCols);

  // Return the broadcasted matrices
  return [aBroadcasted, bBroadcasted];
}