Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

share|improve this question

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  
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/… –  Artes May 24 '13 at 1: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 1: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 3:51

2 Answers 2

up vote 4 down vote accepted

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

share|improve this answer

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.

share|improve this answer

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