2013-11-26 41 views

回答

2

可以使用均勻分佈來生成隨機數:

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

現在設置對角項爲零(as discussed here by Jonas):

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

對稱部件:

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

實施例對於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 

編輯:在randomatlabuser的建議,加到線calc下矩陣的對稱分量並消除循環來在對角線上

+1

注歸零條目當前版本返回一個不對稱的矩陣。此外,可以避免循環:'a(1:(n + 1):end)= 0;' – randomatlabuser

+1

@randomatlabuser,是的感謝您對此的說明,我忘記了對稱性要求。我編輯了我的答案,以包括這一點。 –

+1

@roybatty,謝謝,如果你喜歡,你也可以在你的答案中刪除循環。 – randomatlabuser

2

這是做這件事:

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 
相關問題