Sivakumar V
Sivakumar V

Reputation: 35

How to generate random symmetric 0-1 matrices with a limited number of 1's in each row

I am forming a connectivity matrix such that I want to limit number of 1's in each row. For eg if input size is 15, 30, 80 , 100, highest degree of connectivity should be limited such that 6 , 8, 8, 9. The condition is i) at least one 1 should be there in each row, ii) diagonal should be 0 and iii) matrix should be symmetric.I have tried this code but it doesn't limits the ones when input size became higher.

  m = input('No. OF ROWS AND COLUMNS : ');
  P = rand(m,m); %// generate random numbers in [0,1]
  p=0.4;
  result = rand(m,m)<p; %// generate matrix
  result(bsxfun(@plus, floor(m*rand(1,m))*m, 1:m)) = 1;
  for i=1:m
   for j=1:m
     result(j,i)=result(i,j);
   end
  end
  result(logical(eye(size(result)))) = 0
  A=sum(result)

Upvotes: 1

Views: 234

Answers (1)

user3717023
user3717023

Reputation:

An important consideration is that you want a random matrix; otherwise, just placing 1s above and below the diagonal would be enough. When talking about random things, one usually has some distribution in mind, but you haven't specified any.

You are using p = 0.4 as the probability of having 1 in any entry. With input size n, this will result in about 0.4*n entries in each row (some more, some less). Clearly, with n=100 this is way too much if you want at most 9 in each row.

Here is one way to adjust the probability: if the number of 1s is too high, make it smaller, and repeat. For the sizes that you listed, this is reasonably fast.

success = 0;
n = 100;     % size of matrix
k = 9;       % maximal number of 1s
p = 0.5;
A = zeros(n,n);

while (success == 0)
  A = (rand(n,n) < p);
  A(logical(eye(n))) = 0;
  A = max(A, A');
  s = sum(A,1);
  success = 1;
  if min(s) == 0
     success = 0; p = p*2;   % too few 1s, increase p
  end
  if max(s) > k
     success = 0; p = p/2;   % too many 1s, decrease p 
  end
end
disp(A)

The above approach gives a high quality random matrix, with no particular pattern in the entries.

There are other approaches, like repeating the command

A(1:n, randperm(n)) = 1;

several times and then proceeding as above: A = max(A,A'); A(logical(eye(n)))=0;, ... but they introduce some peculiar distribution of 1s which you may not want.

Upvotes: 1

Related Questions