28
$\begingroup$

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?

$\endgroup$
  • 10
    $\begingroup$ Try (VectorQ[#,NumericQ]&) $\endgroup$ – Leonid Shifrin Dec 20 '12 at 13:58
  • $\begingroup$ Do you mean like this? MyFunction[arg_?(VectorQ[#,NumericQ]&)] $\endgroup$ – Cuboid Dec 20 '12 at 14:03
  • 1
    $\begingroup$ Yes, that's right. $\endgroup$ – Leonid Shifrin Dec 20 '12 at 14:05
  • 5
    $\begingroup$ How about just: p : {_?NumericQ ..} $\endgroup$ – wxffles Dec 20 '12 at 18:35
  • 9
    $\begingroup$ ... or just p:{__?NumericQ}? $\endgroup$ – kglr Dec 20 '12 at 19:10
33
$\begingroup$

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}} *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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