operator * method

Matrix operator *(
  1. dynamic other
)

Multiplies this matrix with another matrix or a scalar value.

This method performs the multiplication operation based on the type of other:

  • If other is a Matrix, it performs matrix multiplication. This operation requires the number of columns in this matrix to equal the number of rows in the other matrix.
  • If other is a num, it performs scalar multiplication. Each element in this matrix is multiplied by the other scalar value.

The function does not mutate the original matrix but instead returns a new matrix that is the result of the multiplication operation.

Throws an Exception if:

  • other is a Matrix but the matrices have incompatible sizes for multiplication.
  • other is not a Matrix or a num.

Example:

var matrixA = Matrix([
  [1, 2],
  [3, 4],
]);
var matrixB = Matrix([
  [2, 0],
  [1, 2],
]);
var resultMatrix = matrixA * matrixB;
print(resultMatrix);
// Output:
// 4  4
// 10 8

var scalar = 2;
var resultScalar = matrixA * scalar;
print(resultScalar);
// Output:
// 2  4
// 6  8

Implementation

Matrix operator *(dynamic other) {
  if (other is Matrix) {
    if (columnCount != other.rowCount) {
      throw Exception('Cannot multiply matrices of incompatible sizes');
    }

    // Define the size limit for switching to normal multiplication
    const int sizeLimit =
        64; // Adjust this value based on your performance testing

    // Switch to normal multiplication for small matrices
    if (rowCount <= sizeLimit ||
        columnCount <= sizeLimit ||
        other.columnCount <= sizeLimit) {
      return _normalMultiply(other);
    }

    // Otherwise, use Strassen's algorithm
    return _strassenMultiply(other);
  } else if (other is Vector) {
    if (columnCount != other.length) {
      throw ArgumentError(
          'The number of columns in the matrix must be equal to the length of the vector for multiplication.');
    }

    Vector result = Vector(rowCount);
    for (int i = 0; i < rowCount; i++) {
      for (int j = 0; j < columnCount; j++) {
        result[i] += this[i][j] * other[j];
      }
    }

    return ColumnMatrix(result.toList());
  } else if (other is num || other is Complex) {
    return scale(other);
  } else {
    throw Exception('Invalid operand type ${other.runtimeType}');
  }
}