19
$\begingroup$

Packed arrays can be of type Integer, Real or Complex. Knowing that an array arr is packed, how can I efficiently determine its type?

$\endgroup$
23
$\begingroup$

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 *)
]
$\endgroup$
10
$\begingroup$

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
$\endgroup$
  • $\begingroup$ That's why I expected that there has to be a way to determine the type. Only when I saw NDSolve`FEM`PackedArrayType was I finally convinced that there is not (for M < 10.4). $\endgroup$ – Szabolcs Oct 10 '17 at 9:00
  • $\begingroup$ @Szabolcs hacky approach, but see update. $\endgroup$ – LLlAMnYP Oct 10 '17 at 9:04

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.