32

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?

Cuboid
  • 1,421
  • 11
  • 15

1 Answers1

35

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}} *)
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
Ajasja
  • 13,634
  • 2
  • 46
  • 104