Lisa
Lisa

Reputation: 3181

How to create symmetric zero and one matrix

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?

Upvotes: 2

Views: 1110

Answers (2)

Bruce Dean
Bruce Dean

Reputation: 2828

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

Upvotes: 2

randomatlabuser
randomatlabuser

Reputation: 636

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

Upvotes: 3

Related Questions