0

我有这个部分可以在组中创建一些随机链接。我可以让它更有效率吗?任何想法?

谢谢。

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{:});
4

1 回答 1

1

一个快速的解决方法是在循环之外预分配 m初始化c它们,以删除 if 条件:

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{:});

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

于 2013-04-27T12:33:40.500 回答