# Functions that operate on symbolic matrices?

I'd like to write functions that operate on symbolic matrices, and do nothing when fed anything else.

ClearAll[M, x, n, d, g, f];
\$Assumptions = {M \[Element] Matrices[{2, 2}]}
TensorDimensions[M.M]
(* yields {2,2} *)
f[M_ ] := TensorDimensions[M.M]
f[{{1, 2}, {3, 4}}]
(* yields {2,2} *)
f[M]
(* yields {2,2} *)
f[x]
(* yields TensorDimensions::scdot: Expression x.x contains the scalar subexpression x. >>   TensorDimensions[x.x] ...  I would like to get f[x]*)
f[3.]
(* yields TensorDimensions::scdot: Expression x.x contains the scalar subexpression 3' >>   TensorDimensions[3.3]...  I would like to get f[3.]*)


How do I go about that? Restricting f as in

f[M_  /; M \[Element] Matrices[{2, 2}]] := TensorDimensions[M.M];


does not work. This function returns {2,2} for the numerically defined matrix, but f[M] for the symbolically defined one.

Of course, the above is meaningless as the function definition implies its output {2,2}. So for this to be useful it should work on Matrices[{d,d}] for variable d.

Element per default doesn't seem to use assertions. You can make it use assertions when evaluating whether M is an element of Matrices[{2,2}] by using Refine
 f[M_ /; Refine[M \[Element] Matrices[{2, 2}]]] := TensorDimensions[M.M]

• @Eric Perhaps checking to see if TensorRank evaluates does the trick for you? eg. Head@TensorRank[b] =!= TensorRank Dec 10, 2012 at 13:59