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.

A few months ago I got a simple answer (see: 1 ) to the question of how to force numeric evaluation during use of functions such as NMinimize - namely the use of _?NumericQ in the argument list.

I now have the same problem, only this time the argument to the user-defined function I'm trying to minimize is a list. Is there an equivalent to _?NumericQ for lists?

share|improve this question
8  
Try (VectorQ[#,NumericQ]&) –  Leonid Shifrin Dec 20 '12 at 13:58
    
Do you mean like this? MyFunction[arg_?(VectorQ[#,NumericQ]&)] –  Cuboid Dec 20 '12 at 14:03
1  
Yes, that's right. –  Leonid Shifrin Dec 20 '12 at 14:05
4  
How about just: p : {_?NumericQ ..} –  wxffles Dec 20 '12 at 18:35
7  
... or just p:{__?NumericQ}? –  kguler Dec 20 '12 at 19:10
show 1 more comment

1 Answer 1

You have several options:

foo[arg_?(VectorQ[#,NumericQ]&)] 

foo[arg: {_?NumericQ ..}]

foo[arg: {__?NumericQ}]

For matrices or higher dimensional arrays, the equivalent of VectorQ is MatrixQ and ArrayQ.

It's worth noting that VectorQ[..., NumericQ] (and its relatives MatrixQ and ArrayQ) are highly optimized and will avoid unpacking packed arrays:

match = RandomReal[1, 10^6];
unpacked = Append[match, 1];
nonmatch = Append[match, "x"];

Table[
 Timing[MatchQ[set, _?(VectorQ[#, NumericQ] &)]], {set, {match, 
   unpacked, nonmatch}}]

(* {{0.000016, True}, {0.003106, True}, {0.003184, False}} *)

Table[
 Timing[MatchQ[set, _?(VectorQ[#, NumericQ[#] &] &)]], {set, {match, 
   unpacked, nonmatch}}]

(* {{0.402001, True}, {0.364469, True}, {0.362019, False}} *)

Table[
 Timing[MatchQ[set, {_?NumericQ ..}]], {set, {match, unpacked, 
   nonmatch}}]

(* {{0.266730, True}, {0.231373, True}, {0.229849, False}} *)

Table[
 Timing[MatchQ[set, {__?NumericQ}]], {set, {match, unpacked, 
   nonmatch}}]

(* {{0.226045, True}, {0.158696, True}, {0.160493, False}} *)
share|improve this answer
add comment

Your Answer

 
discard

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.