如何替换“for循环”以使其运行更快

时间:2015-04-11 08:08:08

标签: matlab

我有一个for循环作为我的代码的一部分。它的运行时间太长,特别适用于I的大长度。有没有办法让它更快?

    [temp,I,J] = unique(cc_new,'rows');
    I=sort(I);
    cc_new = cc_new(I,:);
    C = C(I,:);

    n = 0;
    clear K;

    for i = 1 : length(I)-1,
        for j = i+1 : length(I),
            if sum(intersect(cc_new(i,:),cc_new(j,:)))-sum(cc_new(j,:))==0,
                n = n+1;
                K(n) = j;
            end
        end
    end

    if n > 0,
        K=unique(K);
        removed = cc_new(K',:);
        [temp,I]=setdiff(cc_new,removed,'rows');
        I=sort(I);
        cc_new = cc_new(I,:);
        C = C(I,:);
    end

    cc = cc_new;

1 个答案:

答案 0 :(得分:0)

    index0=find (A (:,2 )==0);
    A0=A(index0,:);
    A1=A;
    A1(index0,:) =[]; % A ( : , 2 ) ~= 0
    [ia1,ja1]=size(A1);
    A20 = A1;
    A30 = A20 ( : , 1 );
    A40 = A0 ( : , 1 );
    A50 = [ A30 ; A40 ];
    [~,ix2,~] = unique(A50,'rows');
    A60 = A0;
    ix3 = ix2-ia1;
    A60(ix3,:) = [];
    A21 = A1;
    A31 = A21 ( : , 2 );
    A41 = A0 ( : , 1 );
    A51 = [ A31 ; A41 ];

[~,ix21,~] = unique(A51,'rows');
A61 = A0;
ix31 = ix21-ia1;
A61(ix31,:) = [];
AN = [ A1 ; A60 ; A61 ];