3

我在 MATLAB 中编写了一个代码,它允许我生成一个随机n顶点图,每个顶点都有c固定的邻居,没有循环(注意边是定向的,因此“a 连接到 b”并不意味着“b 连接到 a”)。

但是,它的效率非常低,尤其是当我需要它处理诸如n = 10000和之类的量级时c = 1000。我想知道是否有人可以优化它,或者提出任何建设性的建议?

function [M]=matsrand(n,c)


MM=0;   %arbitrary starting value
while MM ~=n*c

    M = sparse(zeros(n));       
    ctin = zeros(1,n);  


    for i=1:n
        rp = randperm(n);   %generate vector of the randomly permuted order of n vertices
        rp(rp==i)=[];       %get rid of itself to avoid self connection

        noconnect=find(ctin(:)>=c); %generate list that i is not allowed to connect to
        where=ismember(rp,noconnect);   %returns 1 to the subset noconnect in rp
        noconnectind=find(where);

        rp(noconnectind(:))=[];         %remove the neurons i is not allowed to connect to

        if length(rp)<c
            break
        else
            r=rp(1:c);
        end
        M(i,r)=1;
        ctin(r)=ctin(r)+1;

    end
    MM=sum(ctin);
end
4

1 回答 1

1

这会加快速度:

function [M]=matsrand(n,c)

    MM=0;   %arbitrary starting value
    all_nums=1:n;

    while MM ~=n*c

        M = sparse([],[],[],n,n,n*c);
        ctin = zeros(1,n);

        for ii=1:n
            noconnect=ctin>=c;
            noconnect(ii)=true;

            rem_nums = all_nums(~noconnect); % remaining numbers
            rp=randperm(n-sum(noconnect));
            rp = rem_nums(rp); % remaining numbers, hussled

            if numel(rp)<c
                break
            else
                r=rp(1:c);
            end
            M(ii,r)=1;
            ctin(r)=ctin(r)+1;
        end
        MM=sum(ctin);
    end
end

如果内存不是问题,我认为您可以将稀疏矩阵替换为普通的zeros(n,n).

主要问题仍然是你必须击中那个幸运组合。

于 2012-08-08T15:41:31.650 回答