2012-11-17 90 views
3

這裏是調用的輪廓n = 2*10^3; M = DStochMat02(n,ones(n)./n);有沒有更好的方法來隨機生成雙隨機矩陣?

time calls line 
        1 function M = DStochMat02(n,c) 
        2 % Generate a random doubly stochastic matrix using 
        3 % Theorem (Birkhoff [1946], von Neumann [1953]) 
        4 % Any doubly stochastic matrix M can be written as a convex combination 
        5 % of permutation matrices P1,...,Pk (i.e. M = c1*P1+...+ ck*Pk 
        6 % for nonnegative c1,...,ck with c1+...+ck = 1). 
        7 % Complexity: O(n^2) 
        8 % USE: M = DStochMat02(4,[1/2 1/8 1/8 1/4]) 
        9 % Derek O'Connor, Oct 2006, Nov 2012. [email protected] 
    0.02  1 10 M = zeros(n,n); 
< 0.01  1 11 I = eye(n); 
< 0.01  1 12 for k = 1:n 
    1.64 2000 13  pidx = GRPdur(n);         % Random Permutation 
107.72 2000 14  P = I(pidx,:);         % Random P matrix 
    41.09 2000 15  M = M + c(k)*P; 
< 0.01 2000 16 end 


function p = GRPdur(n) 
% ------------------------------------------------------------- 
% Generate a random permutation p(1:n) using Durstenfeld's 
% Shuffle Algorithm, CACM, 1964. 
% See Knuth, Section 3.4.2, TAOCP, Vol 2, 3rd Ed. 
% Complexity: O(n) 
% USE: p = GRPdur(10^7); 
% Derek O'Connor, 8 Dec 2010. [email protected] 
% ------------------------------------------------------------- 

    p = 1:n;     % Start with Identity permutation 
for k = n:-1:2 
    r = 1+floor(rand*k);  % random integer between 1 and k 
    t = p(k); 
    p(k) = p(r);    % Swap(p(r),p(k)). 
    p(r) = t; 
end 
return % GRPdur 
+0

爲什麼不使用標準函數[randperm](http://www.mathworks.com/help/matlab/ref/randperm.html)而不是'GRPdur'? –

+0

@max taldykin因爲舊的randperm是時間和空間效率低下的。最新版本的Matlab使用他們的Durstenfeld算法實現,這是在時間和空間上最優的 –

回答

1

如何改變線路1415以下行:

l = ([ pidx ; 1:n ] - 1) * [1;n] + 1; % convert pairs (pidx,1:n) to linear indices 
M(l) = M(l) + c(k); 

因爲P是很稀疏,也許這將是更有效地增加只有P的非零。

+1

Spot!這是非常好的,和Matt Fighere給出的方法一樣:http://www.mathworks.co.uk/matlabcentral/answers/53957-is-there-a-better-way-to-randomly-generate-a - 雙隨機矩陣它比我的matlab函數快300倍。 –

+0

@ DerekO'Connor我還沒有看到mathworks解決方案 - 很高興知道我的matlab是最新的。謝謝! – Shai