# Evaluate a polynomial at a matrix

I have a polynomial and a matrix, say z^3 + z + 1 and {{1,1,1},{0,0,0},{0,0,0}}. I can use this code:

T = {{1, 1, 1}, {0, 0, 0}, {0, 0, 0}};
T.T.T + T + IdentityMatrix[3]

{{3, 2, 2}, {0, 1, 0}, {0, 0, 1}}


But for polynomials with many terms it becomes tedious to write out the polynomial in terms of matrix products. Is there an automated way to evaluate a polynomial at a matrix.

You can use "ReplaceAll" to replace the symbol in your polynomial by a matrix. But you must also take care to replace "1" by the IdentityMatrix. E.g.:

z^3 + z + 1 /. {1 -> IdentityMatrix[3], z -> {{1, 1, 1}, {0, 0, 0}, {0, 0, 0}} }

(* {{3, 2, 2}, {0, 1, 0}, {0, 0, 1}} *)

• Please note that this applies the powers to each matrix element separately, rather than computing the dot product/matrix power Nov 19, 2022 at 20:44
• Agreed with Lukas. Should easily be fixed by first doing a /. Power -> MatrixPower. Nov 19, 2022 at 21:37

The obvious solution here, of course, is to use MatrixFunction[]:

MatrixFunction[Function[z, z^3 + z + 1], {{1, 1, 1}, {0, 0, 0}, {0, 0, 0}}]
{{3, 2, 2}, {0, 1, 0}, {0, 0, 1}}

• At first we extract the coefficient from the polynomial f[z].
• And them we construct a matrix form of f[m] where m is a matrix. For i>=1, we use MatrixPower[m,i] or Dot @@ ConstantArray[m, i],but for i==0 we use IdentityMatrix since m maybe singular.
Clear[f, m, coef];
f[z_] = z^3 + z + 1;
m = {{1, 1, 1}, {0, 0, 0}, {0, 0, 0}};
coef = CoefficientList[f[z], z]
coef . Prepend[Table[MatrixPower[m, i], {i, 1, Length[coef] - 1}],
IdentityMatrix[Dimensions[m] // First]]
1*IdentityMatrix[3] + 1*m + 0*m . m + 1*m . m . m


• Test another polynomial and another matrix. It indicate that the method by using ReplaceAll is wrong.
Clear[f, m, coef];
f[z_] = 2 z^3 + 3*z^2 + 4 z + 5;
m = {{1, 1, 1}, {1, 1, 0}, {1, 0, 1}};
coef = CoefficientList[f[z], z]
coef . Prepend[Table[MatrixPower[m, i], {i, 1, Length[coef] - 1}],
IdentityMatrix[Dimensions[m] // First]]
5*IdentityMatrix[3] + 4*m + 3*m . m + 2*m . m . m


You could overload some operators use https://reference.wolfram.com/language/ref/TagSetDelayed.html

ClearAll[mat];
mat /: mat[x_] ^ n_ := mat[MatrixPower[x,n]];
mat /: mat[x_] + n_?NumericQ := mat[x + IdentityMatrix[Dimensions[x] // First] * n];
mat /: mat[x_] + mat[y_] := mat[x + y];
z = mat[{{1,1,1},{0,0,0},{0,0,0}}];
z^3 + z + 1

mat[{{3, 2, 2}, {0, 1, 0}, {0, 0, 1}}]