How to correctly replace scalars with matrices?

How can a scalar be replaced with a matrix to perform operations on the matrix, not its elements?

For example,

A = RandomInteger[{-1, 1}, {4, 4}]
Sin[x] /. x -> A


returns something like

{{Sin[1], Sin[1], Sin[1], -Sin[1]},
{-Sin[1], -Sin[1], Sin[1], 0},
{0, -Sin[1], -Sin[1], 0},
{-Sin[1], Sin[1], -Sin[1], Sin[1]}}


• Functions of matrices are tricky beasts, as usually ones needs the eigensystem of the matrix etc. Thus, I don't think this question is well posed Feb 18 at 19:54

"MatrixFunction" will do what you want. Here is an example with "Sqrt":

a = RandomReal[{-1, 1}, {4, 4}];
sq = MatrixFunction[Sqrt, a];

Chop[sq . sq - a]

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


I used "Chop" because of numerical errors due to machine precision.

• Also MatrixPower[sq, 2] - a // Chop Feb 18 at 21:28
• Does it work with user-defined things? Will something like MatrixFunction[Sin/2 + Sqrt + 1, a] work? Feb 18 at 23:00
• @homocomputeris For that, you'll need to define a pure function: MatrixFunction[Sin[#]/2 + Sqrt[#] + 1 &, a]. Feb 19 at 2:26