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


2 Answers 2


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:

(* Integer *)

(* $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];
"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]] &
  • $\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, 2017 at 9:00
  • $\begingroup$ @Szabolcs hacky approach, but see update. $\endgroup$
    – LLlAMnYP
    Oct 10, 2017 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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