Symmetric binary matrix with diagonal 0 values

조회 수: 2 (최근 30일)
Dina Tarek
Dina Tarek 2019년 10월 21일
댓글: Guillaume 2019년 11월 25일
I want to create a symmetric (10x10) binary matrix with n number of ones and the diagonal values ​​have to be 0s. Can anyone help me?
  댓글 수: 1
James Tursa
James Tursa 2019년 10월 21일
1's can be located anywhere, just not on the diagonal? Random locations? I am assuming n must be even?

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2019년 10월 21일
Guaranteed to work on the first try:
Msize = 10; %size of square matrix
N = 20; %number of ones on each side of the diagonale
M = zeros(Msize);
indices = nonzeros(tril(reshape(1:Msize^2, Msize, Msize), -1)); %get indices BELOW diagonale
M(indices(randperm(numel(indices), N))) = 1; %pick N indices and fill with 1
M = M | M.' %do the symmetry
  댓글 수: 3
Dina Tarek
Dina Tarek 2019년 11월 25일
Error using randperm
Inputs must be nonnegative scalar integers.
The above message appeared when I tried diffrent Msize
for example Msize = 12 or 13 or 9 ;
do you know how to solve this error
Guillaume
Guillaume 2019년 11월 25일
Your N is either non-integer, non-positive, or non-scalar.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2019년 10월 21일
편집: KALYAN ACHARJYA 2019년 10월 21일
Beware: Before Try (I posted it as answer, so that you may get some idea)
n=input('Eneter the value of n: ')
result=zeros(10,10);
while sum(result)~=n
result=ones(10,10)-diag(diag(ones(10,10))) & randi([0 1],[10 10]);
end
result
When it will works, depending on luck, as I have no idea how to control number on 1 generation in random matrics, but I have forced all diagonal elements to zeros.
During running the Matlab (Execution), you can stop it by pression Ctrl+S

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by