3

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:

myfunction[W_?matrixnumQ]:=W

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:

myfunction[W_?MatrixQ[#,NumericQ]&]:=W

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

Jonathan Shock
  • 3,015
  • 15
  • 24
  • 1
    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: http://mathematica.stackexchange.com/questions/533/placement-of-condition-expressions – Artes May 24 '13 at 01:01
  • 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. – Jonathan Shock May 24 '13 at 01:02
  • 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. – Leonid Shifrin May 24 '13 at 11:20
  • Thanks @LeonidShifrin, I would consider that a duplicate and will flag it as such. Thank you. – Jonathan Shock May 25 '13 at 03:51

2 Answers2

4

More straightforward approach would be this:

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

e.g.

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

an example:

myfunction[{{1, 3}, {-2, -3}}]
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

Artes
  • 57,212
  • 12
  • 157
  • 245
1

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.

Jonathan Shock
  • 3,015
  • 15
  • 24