matlab更高效的随机链接创建

时间:2013-04-27 11:41:41

标签: matlab random graph matrix

我有这一部分在组中制作一些随机链接。我可以提高效率吗?有什么想法吗?

感谢。

n=[10 ;10 ;10];
no_of_groups=size(n,1);
for k=1:no_of_groups
    if k==1
        m{k,1}=randi(n(1), n(1),2);%random links between nodes of group1
        m1=rand(n(1),1)/2+0.5;%random weight to edges
        c{k,1} = cat(2,m{1},m1);
    else
        m{k,1}=randi([((k-1)*n(k-1)+1) (k*n(k))],n(k),2););%random links between nodes of group k
        m1=rand(n(k),1)/2+0.5;
        c{k,1} = cat(2,m{k,1},m1);
    end
end
c=cat(1,c{:});

1 个答案:

答案 0 :(得分:1)

快速解决方法是在循环外预分配 mc以及 initiliaze 以删除if条件:< / p>

n  = [10 ;10 ;10];
no = size(n,1);

% Preallocate
m = cell(no,1);
c = cell(no,1);

% Initialize m and c
m{1} = randi(n(1), n(1),2);%random links between nodes of group1
m1   = rand(n(1),1)/2+0.5;%random weight to edges
c{1} = cat(2,m{1},m1);

for k = 2:no
        m{k} = randi([(k-1)*n(k-1)+1 k*n(k)],n(k),2);%random links between nodes of group k
        m1   = rand(n(k),1)/2+0.5;
        c{k} = cat(2,m{k,1},m1);
end
c=cat(1,c{:});

这个循环是可矢量化的,或者至少可以避免使用单元格,这样可以提高速度。