2

I need to create a 100*100 symmetric matrix that has random distribution of zeros and ones, but the diagonal should be all zeros, how can I do that?

Lisa
  • 3,121
  • 15
  • 53
  • 85

2 Answers2

3

This is one way to do it:

N = 100; % size of square matrix
p = 0.5; % probability of 0s
A = triu(rand(N)>p, 1); % matrix of 0s and 1s (upper triangular part)
A = A + A'; % now it is symmetric
randomatlabuser
  • 626
  • 4
  • 13
2

You can use a uniform distribution to generate your random numbers:

n = 100;
a = round(rand(n,n));

Now set the diagonal entries to zero (as discussed here by Jonas):

a(logical(eye(size(a)))) = 0;

Symmetric component:

aSym = floor((a + a')/2);

Example for n = 5:

aSym =

     0     0     0     0     0
     0     0     1     0     1
     0     1     0     0     1
     0     0     0     0     0
     0     1     1     0     0

Edit: At randomatlabuser's suggestion, added line to calc the symmetric component of the matrix and eliminated loop to zero out entries on the diagonal

Community
  • 1
  • 1
Bruce Dean
  • 2,798
  • 2
  • 18
  • 30