Matlab: all binary matrix combinations

I am looking for an easy way to get all combinations of a binary matrix. I already tried the perms() function, but did not get the correct result.

I have, for example, a matrix N x N filled with 1 and -1. For N = 2, there would be 2 ^ 4 possible combinations of 1 and -1, similar

  (1 1) (1 1) (-1 -1) M(1) = (1 1) , M(2) = (1 -1) , M(3) = ( 1 1) and so on... 

When I use perms (), I do not get, for example, the first matrix.

How can i fix this?

+5
source share
3 answers

You can represent all numbers between 0 and 2^(N^2)-1 as binary numbers, and then change:

 N = 2; v = (1:2^(N^2))-1; A = dec2bin(v)' - '0'; %'// Or use: decimalToBinaryVector(v)'; A(A==0) = -1; A = reshape(A,N,N,2^(N^2)); 
+5
source

A simple hack is this:

 v = [1 -1 1 -1]; P = perms(v); for ii = 1:size(P,1) A = reshape(P(ii,:),2,2) end 

that leads to:

 A = -1 -1 1 1 ... 

There are still some identical matrices as a result that should be removed.

-1
source

I think I found a solution to my problem

 L = 2; N = L^2; v = cell(N,1); for k = 1:N v{k} = linspace(-1,1,2); end ne=numel(v); x=cell(ne,1); [x{1:ne,1}]=ndgrid(v{end:-1:1}); p=reshape(cat(ne+1,x{:}),[],ne); F = cell(length(p),1); for k=1:length(p) F{k} = reshape(p(k,:),L,L); end 
-1
source

Source: https://habr.com/ru/post/1239717/


All Articles