How can I determine the type of a packed array?
We can use one of several ways. First, let us create some test data:
arr = Range[10]; (* this is an Integer packed array *)
unpacked = {1, 2, 3} (* this is an Integer array that is NOT packed *)
Since Mathematica 10.4, Internal`PackedArrayType
directly returns the type:
Internal`PackedArrayType[arr]
(* Integer *)
Internal`PackedArrayType[unpacked]
(* $Failed *)
Developer`PackedArrayQ
has a second argument, which is the type of the array. This way we can test both for the type and "packedness" at the same time.
Developer`PackedArrayQ[arr, Integer]
(* True *)
Developer`PackedArrayQ[arr, Real]
(* False *)
Developer`PackedArrayQ[unpacked, Integer]
(* False *)
This function is useful in specializing functions for processing packed array of various types, e.g. to dispatch to the appropriate LibraryLink function. A third argument allows testing for the array depth as well.
To get the type directly in versions of Mathematica prior to 10.4, without testing for each possible type using PackedArrayQ
, we can extract an element and check its head:
packedArrayType[arr_?Developer`PackedArrayQ] := Head@Extract[arr, Table[1, {ArrayDepth[arr]}]]
packedArrayType[___] := $Failed
This is roughly what NDSolve`FEM`PackedArrayType
does, which confirms to me that this is the appropriate way. In a package, I would define packedArrayType
in a version-dependent manner as
If[$VersionNumber >= 10.4,
packedArrayType = Internal`PackedArrayType,
packedArrayType[...] := (* manual method from above *)
]
There's another useful function for this kind of thing
arr = RandomReal[1, 10^8];
Developer`PackedArrayForm[arr]
"PackedArray"[Real, "<" 100000000 ">"]
The drawback is that this is for display purposes only, it doesn't seem to be possible to extract the Real
from this.
on second thoughts, this seems to work:
Developer`PackedArrayForm[Range[10]] // ToBoxes // MakeExpression // #[[1, 1]] &
Integer