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}]}
(* yields {2,2} *)
f[M_ ] := TensorDimensions[M.M] 
f[{{1, 2}, {3, 4}}]  
(* yields {2,2} *)
(* yields {2,2} *)
(* yields TensorDimensions::scdot: Expression x.x contains the scalar subexpression x. >>   TensorDimensions[x.x] ...  I would like to get f[x]*)
(* 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.


1 Answer 1


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]
  • $\begingroup$ Thanks -- that gets me partially there. How would I make the function operate on matrices of variable dimensions as in f[M_ /; Refine[M [Element] Matrices[{d, d}]]] := TensorDimensions[M.M] $\endgroup$
    – Eric
    Dec 10, 2012 at 13:45
  • $\begingroup$ @Eric Perhaps checking to see if TensorRank evaluates does the trick for you? eg. Head@TensorRank[b] =!= TensorRank $\endgroup$
    – jVincent
    Dec 10, 2012 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.