Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate all (0,1) nxn matrices

While working on a problem related to Weisstein's Conjecture (https://cs.uwaterloo.ca/journals/JIS/VOL7/Sloane/sloane15.pdf), I needed to generate all n x n (0,1) matrices for n = 2, 3, 4,... It is not too hard if you think about the right binary sequences and partition them accordingly. For example, here are all the 3 x 3 matrices:

With[{n = 3}, 
 lis = PadLeft[IntegerDigits[#, 2], n^2]& /@ Range[0, 2^n^2 - 1]; 
 mats = (Partition[#, n] & ) /@ lis
]; 

Weisstein's Conjecture involves, for each n = 2, 3, ..., counting the number of matrices whose eigenvalues are all real and positive. For n = 2, there are 3; for n = 3, there are 25; for n = 4, there are 543; and so on. The eigenvalue computations are time-consuming but straightforward.

What I was interested in though, was finding other ways of enumerating the n x n matrices. To get all of them I used the base 2 representations of the integers up to 2^(n^2) and partitioned to make the matrices. There must be other (more efficient?) ways.

like image 349
Paul Wellin Avatar asked Dec 30 '12 06:12

Paul Wellin


1 Answers

We can use built in Mathematica function Tuples. Your 3x3 example simply becomes

ms = Tuples[{1, 0}, {3, 3}];

The enumeration of orderings can be done by binary numbers

FromDigits[#, 2] & /@ Flatten /@ ms

enter image description here

To visualize the orderings:

ArrayPlot[#, ImageSize -> 20, Mesh -> All] & /@ ms

enter image description here

like image 140
Vitaliy Kaurov Avatar answered Nov 16 '22 16:11

Vitaliy Kaurov