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?
Asked
Active
Viewed 1,086 times
2 Answers
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
-
1Note that the current version returns a matrix that is not symmetric. Also, the loop can be avoided: `a(1:(n+1):end) = 0;` – randomatlabuser Nov 26 '13 at 05:34
-
1@randomatlabuser, yes thanks for your note on this, I had forgotten the symmetry requirement. I edited my answer to include that. – Bruce Dean Nov 26 '13 at 06:09
-
1@roybatty, thank you, if you like you can also remove the loop in your answer. – randomatlabuser Nov 26 '13 at 06:14
-
@randomatlabuser, thanks for your suggestion on the loop (see edit), keep up the great work! – Bruce Dean Nov 26 '13 at 06:27