/// <summary> /// Multiplies a matrix by itself <c>n</c> times. /// </summary> /// public static double[,] Power(this double[,] matrix, int n) { if (matrix == null) { throw new ArgumentNullException("matrix"); } if (!matrix.IsSquare()) { throw new ArgumentException("Matrix must be square", "matrix"); } if (n == 0) { return(Matrix.Identity(matrix.GetLength(0))); } // TODO: Reduce the number of memory allocations // TODO: Use bitwise operations instead of strings double[,] result = matrix; string bin = System.Convert.ToString(n, 2); for (int i = 1; i < bin.Length; i++) { result = Matrix.Dot(result, result); if (bin[i] == '1') { result = Matrix.Dot(result, matrix); } } return(result); }