Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 1 down vote accepted

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]
share|improve this answer
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] – Eric Dec 10 '12 at 13:45
@Eric Perhaps checking to see if TensorRank evaluates does the trick for you? eg. Head@TensorRank[b] =!= TensorRank – jVincent Dec 10 '12 at 13:59

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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