operator ^ method

Matrix operator ^(
  1. int exponent
)

Raises this matrix to the power of the given exponent using exponentiation by squaring.

exponent: The non-negative integer exponent to raise this matrix to.

Returns a new matrix containing the result of the exponentiation.

Example:

var matrix = Matrix([[1, 2], [3, 4]]);
var result = matrix ^ 2;
print(result);
// Output:
// 7   10
// 15  22

Implementation

Matrix operator ^(int exponent) {
  if (rowCount != columnCount) {
    throw Exception('Cannot exponentiate non-square matrix');
  }

  if (exponent < 0) {
    throw Exception('Exponent must be a non-negative integer');
  }

  Matrix result = Matrix.eye(rowCount);
  Matrix base = Matrix(_data.map((row) => List<dynamic>.from(row)).toList());

  while (exponent > 0) {
    if (exponent % 2 == 1) {
      result = result.dot(base);
    }
    base = base.dot(base);
    exponent ~/= 2;
  }

  return result;
}