# Why does this substitution not work?

Sqrt[Matrix[( {
{0, 1},
{-1, 0}
} )]] /. f_[Matrix[x__]] :> Matrix[MatrixFunction[f, x]]


Matrix is an undefined symbol but I want to define some substitutions with it.

• For those searching for a similar question in the future please make the title more informative. For example " function substitution not matching with Sqrt" Commented Nov 2, 2022 at 19:51

I assume this is related to that other question you recently posted--maybe merge them? Anyway, I'm going to change MatrixFunction for now to hopefully get a clearer answer. Your pattern matched an expression whose body only had one argument. You need to add something to the pattern to match more arguments. Try something like this:

Sqrt[Matrix[({{0, 1}, {-1, 0}})]] /.
f_[Matrix[mat_], args___] :> Matrix[MatrixFunction[f[#, args] &, mat]]


Matrix[MatrixFunction[Sqrt[#1] & , {{0, 1}, {-1, 0}}]]

(Thanks BobHanlon)

• What is MatrixFn? Commented Nov 2, 2022 at 19:01
• The RHS of the rule should be Matrix[MatrixFn[f[#, args]&, mat]] Commented Nov 2, 2022 at 19:01
• @BobHanlon thanks, works! Commented Nov 2, 2022 at 19:05
• @Anixx, I don't know what to expect from MatrixFunction, so I chose something else to make verifying the result easier. As it turns out, I still screwed that up because I forgot it was the f that needed to be applied. Commented Nov 2, 2022 at 19:19
• Thanks @BobHanlon! Commented Nov 2, 2022 at 19:20

If you look at the FullForm of Sqrt, you see that it is silently converted to a Power, a function taking two arguments, not one. Your pattern only matches functions of a single argument.

FullForm[Sqrt[x]]
(* Power[x, Rational[1, 2]]*)


As explained by @Mikado Sqrt is converted to Power which takes two arguments. One solution is to define:

sqrt=Inactive[Sqrt]


and then use sqrt instead like

sqrt[Matrix[({{0, 1}, {-1, 0}})]] /.
f_[Matrix[x__]] :> Matrix[MatrixFunction[Activate@f, x]]


If it is too late and you already used Sqrt at multiple parts in the notebook then you can use:

Hold[Sqrt[Matrix[({{0, 1}, {-1, 0}})]]] /.
f_[Matrix[x__]] :> Matrix[MatrixFunction[f, x]] // ReleaseHold


Or

Sqrt[Matrix[({{0, 1}, {-1, 0}})]] /. Sqrt[s_] -> Inactive[Sqrt][s]  /.
f_[Matrix[x__]] :> Matrix[MatrixFunction[Activate@f, x]]


Notice that I used Sqrt[s_] -> Inactive[Sqrt][s] instead of Sqrt -> Inactive[Sqrt] because I am allowing Sqrt[s_] to be converted to

Power[Pattern[s,Blank[]],Rational[1,2]]

If I had a bad idea and used HoldPattern :

Sqrt[Matrix[({{0, 1}, {-1, 0}})]] /.
HoldPattern[Sqrt[s_]] -> Inactive[Sqrt][s]


Then it would not work because It would not convert to Power. If the Sqrt was a Cos then HoldPattern would work :

Cos[Matrix[({{0, 1}, {-1, 0}})]] /.
HoldPattern[Cos[s_]] -> Inactive[Cos][s]


because there is nothing to worry about concerning hidden transformations in that case (there can be in other cases because of the parity of Cos which leads to argument reordering).