3
$\begingroup$

This question already has an answer here:

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

$\endgroup$

marked as duplicate by rm -rf May 25 '13 at 3:59

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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 May 24 '13 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$ – Jonathan Shock May 24 '13 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$ – Leonid Shifrin May 24 '13 at 11:20
  • $\begingroup$ Thanks @LeonidShifrin, I would consider that a duplicate and will flag it as such. Thank you. $\endgroup$ – Jonathan Shock May 25 '13 at 3:51
4
$\begingroup$

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

$\endgroup$
1
$\begingroup$

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.

$\endgroup$

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