Search code examples
matlabhamming-distance

Finding a binary matrix such that the given hamming weight is constant


Given a square binary matrix. I want to get all possible binary matrices which are at d Hamming distance apart.

Suppose

A=[1 0 1; 
   0 1 1; 
   1 1 0]. 

Then a matrix which is one (d) Hamming distance apart is

[0 0 1; 
 0 1 1; 
 1 1 0].

Any help in Matlab base coding?


Solution

  • I am hoping that I got the definition of hamming weight right in the given context. Based on that hope/assumption, this might be what you were after -

    combs = dec2base(0:2^9-1,2,9)-'0'; %//'# Find all combinations
    combs_3d = reshape(combs',3,3,[]); %//'# Reshape into a 3D array
    
    %// Calculate the hamming weights between A and all combinations.
    %// Choose the ones with hamming weights equal to `1`
    out = combs_3d(:,:,sum(sum(abs(bsxfun(@minus,A,combs_3d)),2),1)==1)
    

    Thus, each 3D slice of out would give you such a 3 x 3 matrix with 1 hamming weight between them and A.

    It looks like you have 9 such matrices -

    out(:,:,1) =
         0     0     1
         0     1     1
         1     1     0
    out(:,:,2) =
         1     0     1
         0     1     1
         0     1     0
    out(:,:,3) =
         1     0     1
         0     0     1
         1     1     0
    out(:,:,4) =
         1     0     1
         0     1     1
         1     0     0
    out(:,:,5) =
         1     0     0
         0     1     1
         1     1     0
    out(:,:,6) =
         1     0     1
         0     1     0
         1     1     0
    out(:,:,7) =
         1     0     1
         0     1     1
         1     1     1
    out(:,:,8) =
         1     1     1
         0     1     1
         1     1     0
    out(:,:,9) =
         1     0     1
         1     1     1
         1     1     0
    

    Edit

    For big n, you need to use loops it seems -

    n = size(A,1);
    nsq = n^2;
    
    A_col = A(:).';
    out = zeros(n,n,nsq);
    count = 1;
    for k1 = 0:2^nsq-1
        match1 = dec2bin(k1,nsq)-'0';
        if sum(abs(match1-A_col))==1
            out(:,:,count) = reshape(match1,n,n);
            count = count + 1;
        end
    end