在MATLAB中查找和排序的更快的替代方案

时间:2017-11-23 14:16:54

标签: matlab sorting find

我正在使用遗传算法进行社区检测。社区以基于位点的表示形式表示,每个索引(基因)及其值都在同一社区中。

例如,在下图中,如果染色体是(b),社区将是(d)

locus-based representation

所以要从染色体中提取社区,我需要迭代地找到索引和值,为此,我编写了这段代码:

while (SumComms)~=nVar
    j=find(Sol>0,1,'first');%find the first node which has not placed in any community
    Com=[j,Sol(j)];%index of the node and it's value
    Comsize=0;
    while Comsize<numel(Com)
        Comsize=numel(Com);
        x=find(ismembc(Sol,sort([Com,Sol(Com)])));%Indexes which Com occure in Sol
        Com=unique([Com,x,Sol(x)]);
    end
    Sol(Com)=0;
    i=i+1;
    SumComms=SumComms+numel(Com);
    Communities{i}=Com;
end

但即使是中型网络,x=find(ismembc(Sol,sort([Com,Sol(Com)])))也非常耗时。你知道更快的方式吗?

1 个答案:

答案 0 :(得分:1)

这是使用逻辑向量的解决方案。我们可以将Com定义为逻辑向量,而不是对索引进行操作,因此可以将对ismember等索引的操作简化为索引操作:

i=0;
SumComms=0;
nVar = 9;
Sol = [3 0 3 1 5 6 4 7 7]+1;
while SumComms ~= nVar
    j=find(Sol>1,1,'first');
    Com = false(1,nVar);
    Com([j Sol(j)])=true;
    Comsize=0;
    sumcom = 2;
    while Comsize<sumcom
        Comsize=sum(Com);
        Com(Sol(Com))=true;
        Com = Com(Sol);
        Com(Sol(Com))=true;
        sumcom = sum(Com);
    end
    Sol(Com)=1;
    i = i + 1;
    SumComms=SumComms+sumcom;
    Communities{i}=find(Com);
end

Octave测试结果表明,所提方法至少比原方法快10倍。