# How to replace variables with matrices form rather than as lists form?

According to an example of Cayley–Hamilton theorem,

m = {{1, 2},{3, 4}};
mc = m~CharacteristicPolynomial~λ


Output: $\lambda ^2-5 \lambda -2$

mc /. λ -> m // MatrixForm


Output: $\left( \begin{array}{cc} -6 & -8 \\ -8 & -6 \\ \end{array} \right)$ (This is obviously wrong.)

-2 IdentityMatrix@2 - 5 m + m.m // MatrixForm


Output: $\left( \begin{array}{cc} 0 & 0 \\ 0 & 0 \\ \end{array} \right)$ (This is the correct result, but how to perform with Replace etc.?)

• As you're probably aware, Power is not the same as MatrixPower, and -2 is not the same as -2 IdentityMatrix[2]. You can get some of the way there with -2 - 5 λ + λ^2 /. {λ -> m, Power -> MatrixPower}, but I don't have a clean way to deal with -2. Dec 11, 2017 at 11:44
• Expand[im mc] /. {Power -> MatrixPower, λ -> m, im -> IdentityMatrix[2]}?
– kglr
Dec 11, 2017 at 11:45

IdentityMatrix[2] (mc /. {Power -> MatrixPower, λ -> m})


{{0, 0}, {0, 0}}

or

im mc /. {Power -> MatrixPower, λ -> m, im -> IdentityMatrix[2]}


{{0, 0}, {0, 0}}

From the docs for MatrixPower:

An easy way to evaluate a matrix polynomial:

mpe[p_, x_, m_] := Module[{cl = CoefficientList[p, x]},
Sum[MatrixPower[m, i - 1] cl[[i]], {i, Length[cl]}]]

mpe[1 + 2 x + 3 x^3, x, {{1, 2}, {3, 4}}]

(*  {{114, 166}, {249, 363}}  *)


The problem that follows this one in the docs is to evaluate the characteristic polynomial on a matrix, which we apply below to the OP's example:

mpe[mc, λ, m]
(*  {{0, 0}, {0, 0}}  *)


You can use MatrixFunction:

MatrixFunction[
Function[λ, Evaluate[mc]],
m
] //Simplify


{{0, 0}, {0, 0}}

• Thanks. But this way (0.013542s) is significantly slower 290 times than that of @kglr's answer (0.000046s).
– ooo
Dec 11, 2017 at 14:43