如何在MATLAB中用c个固定邻居创建n个顶点的随机图?

时间:2012-08-08 14:54:33

标签: matlab graph-theory

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

然而,它非常低效,特别是当我需要它在n = 10000c = 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

1 个答案:

答案 0 :(得分: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)替换稀疏矩阵。

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