I am looking for the fastest way to test whether an n-dimensional numerical (NumericQ
) array (in the ArrayQ
sense) is complex or not. It is considered complex if it has at least one complex element.
It is an important requirement that this test must not unpack packed arrays.
Currently I have Not@ArrayQ[arr, _, FreeQ[#, _Complex] &]
, which does not unpack, but it executes the test for each element of packed arrays (can be tested using Print
). Theoretically it's sufficient to test only one: all elements of a packed array are necessarily of the same type. In theory it's possible to detect whether an array is packed, and if it is, only test the first element, but this is very ugly, so I'd like to avoid it. It' also not easy to implement for an n-dimensional array.
What I am hoping for is a function which is internally special cased for packed arrays and is thus very fast.
PackedArrayQ[arr, Complex] || Not@ArrayQ[arr, _, FreeQ[#, _Complex] &]
(I don't know how to check ifPackedArrayQ
unpacks and/or tests each element) Edit: Needs["Developer`"] $\endgroup$Deverloper`PackedArrayQ[arr, Complex] || (Not@Developer`PackedArrayQ[arr] && Not@FreeQ[arr, Complex])
. Care to post an answer? $\endgroup$NumericQ
). If it has at least one complex element, it is considered to be complex. This is why I hadNot@ ... FreeQ
instead ofMemberQ
. Use case: need to decide how to transfer the data through MathLink so it's easy to handle in C on the other side. $\endgroup$