# Quick way to tell if matrix is integer-only?

What's the most shortest one-liner code to tell whether a matrix is integer-only?

I've come up with:

 Length@Cases[A // Flatten, _?(Not@*IntegerQ)] == 0


but isn't there a better, more readable way?

• See MatrixQ[matrix, test]. You can apply a test to each element. – Ymareth Oct 29 '14 at 14:11
• @Ymareth beat me to it by a minute! :-) – dr.blochwave Oct 29 '14 at 14:37
• I did write a bit less :) – Ymareth Oct 29 '14 at 15:32

You could try this, which is straightforward:

A = {{0.5, 1}, {2, 3}};

MatrixQ[A, IntegerQ]
(* False *)


Or alternatively - still pretty readable though!

ArrayQ[A, _, IntegerQ]
(* False *)


This has the added bonus of being applicable to other arrays, for example:

integerMatrix = RandomInteger[10, {10, 10, 10}];

ArrayDepth@integerMatrix
(* 3 *)

MatrixQ[integerMatrix, IntegerQ]
(* False *)

ArrayQ[integerMatrix, _, IntegerQ]
(* True *)


Building on that, here's a performance test with a big matrix...

(* Make a big integer matrix *)
A = RandomInteger[100, {2000, 2000}];

Length@Cases[A // Flatten, _?(Not@*IntegerQ)] == 0 // AbsoluteTiming
(* 2.71 seconds, True *)

MatrixQ[A, IntegerQ] // AbsoluteTiming
(* 0.000005 seconds, True *)

ArrayQ[A, _, IntegerQ] // AbsoluteTiming
(* 0.00001 seconds, True *)

• Note that the various array Q functions are optimized for packed arrays. The timing is independent of the size of the array, I believe, for testing whether it is a packed array of integers or reals. Hence the performance difference in your last example. – Michael E2 Oct 29 '14 at 14:53
• Thanks @MichaelE2 - I'd just noticed that but wasn't sure why! The comparison was more between these and the OPs example. – dr.blochwave Oct 29 '14 at 14:55