2
$\begingroup$

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?

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

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 *)
|improve this answer|||||
$\endgroup$
  • 2
    $\begingroup$ 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. $\endgroup$ – Michael E2 Oct 29 '14 at 14:53
  • $\begingroup$ Thanks @MichaelE2 - I'd just noticed that but wasn't sure why! The comparison was more between these and the OPs example. $\endgroup$ – dr.blochwave Oct 29 '14 at 14:55

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.