做者:凱魯嘎吉 - 博客園 http://www.cnblogs.com/kailugaji/html
雙隨機矩陣(doubly stochastic matrix):元素屬於[0,1],行和爲1,且列和爲1。數組
function A=doubly_stochastic(n) %產生 n 階雙隨機矩陣 A A(1,1)=rand; for i=2:n-1 d=1-sum(A(1,1:i-1)); A(1,i)=d*rand; end for i=2:n-1 d=1-sum(A(1:i-1,1)); A(i,1)=d*rand; end for i=2:n-1 for j=2:n-1 d1=1-sum(A(i,1:j-1)); d2=1-sum(A(1:i-1,j)); d=min([d1 d2]); A(i,j)=d*rand; end end for i=1:n-1 A(n,i)=1-sum(A(1:n-1,i)); end for i=1:n A(i,n)=1-sum(A(i,1:n-1)); end if A(n,n)<0 A=1/n*ones(n); end %對稱化A A=(A'+A)/2;
注:程序最後一行若是去掉,則爲雙隨機矩陣,加上最後一行,保證矩陣爲對稱陣。spa
>> A=doubly_stochastic(5) A = 0.3260 0.2105 0.3017 0.1032 0.0585 0.2105 0.1132 0.4114 0.1341 0.1308 0.3017 0.4114 0.0023 0.1947 0.0899 0.1032 0.1341 0.1947 0.3641 0.2039 0.0585 0.1308 0.0899 0.2039 0.5169 >> sum(A, 1) ans = 1 1 1 1 1 >> sum(A, 2) ans = 1 1 1 1 1 >> A'==A ans = 5×5 logical 數組 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1