In this question. I suggested that to test whether the input of a function was a matrix of numbers one could create the following test:

matrixnumQ[exp_] := MatrixQ[exp, NumericQ]

and then define the function as:


This is simple enough in this case but is there a way to test patterns on inputs in a single line if the pattern test is more complex than that above. Something like:


This clearly doesn't work but just to give you the idea of what I'm looking for

  • 1
    $\begingroup$ You'd better use Condition (/;) taking e.g. Det[W] as a definition, e.g. myfunction[W_ /; MatrixQ[W, NumericQ]] := Det[W]. This question should be interesting: mathematica.stackexchange.com/questions/533/… $\endgroup$
    – Artes
    Commented May 24, 2013 at 1:01
  • $\begingroup$ Thanks @Artes, I wrote an answer below using /; after finding it in another question. Your implementation is better though. If you want to write this as an answer, I'll accept it. $\endgroup$ Commented May 24, 2013 at 1:02
  • $\begingroup$ The last line in your post will work - you just need extra parentheses: myfunction[W_?(MatrixQ[#,NumericQ]&)]. See this question for an explanation. If this was the main difficulty you had here, I'd consider this question a duplicate. $\endgroup$ Commented May 24, 2013 at 11:20
  • $\begingroup$ Thanks @LeonidShifrin, I would consider that a duplicate and will flag it as such. Thank you. $\endgroup$ Commented May 25, 2013 at 3:51

2 Answers 2


More straightforward approach would be this:

myfunction[W_ /; MatrixQ[W, NumericQ]]:= definition


myfunction[ W_ /; MatrixQ[W, NumericQ]]:= Det[W]

an example:

myfunction[{{1, 3}, {-2, -3}}]

if e.g. the input is not a matrix or doesn't satisfy the condition then the function is unevaluated

myfunction[{{a, b}, {c, d}}]
 myfunction[{{a, b}, {c, d}}]

I'd recommend this post Using a PatternTest versus a Condition for pattern matching


OK, I think I figured it out from this question. The answer seems to be:

myfunction[W_?MatrixQ /; Apply[And, NumericQ[#] & /@ Flatten[W]]] := W

Any other suggestions would be great to know.


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