在Matlab中获得组合的快速算法?

时间:2014-05-06 21:46:22

标签: matlab

我需要在Matlab中调整以下算法,因为步骤(2)中的双循环需要很长时间n很大(我应该能够为n=15运行算法)。有什么想法吗?

n=3; 

% (1) construct A: list of DISPOSITIONS of the elements of the set {0,1} in n 
%places (organise 2 elements in n places with possibility of repetitions and        the order matters) 

A=makeindex(n); %matrix 2^n x n (FAST)

% (2) modify A: it should give the list of COMBINATIONS of the elements of the set 
%{0,1} in n-1 places (organise 2 elements in n-1 places with repetitions and the 
%order does NOT matter), repeated twice:
% once when the n-th element is 0, the other when the n-th element is 1
Xr=A(:,n);  
m=sum(A,2);        %vector totalx1
                   %each element is the total number of ones in the
                   %corresponding row


drop=false(2^n,1);   %logical vector totalx1

for i=1:2^n
    parfor j=1:2^n
        if j>i
            if m(i)==m(j) && Xr(i)==Xr(j)  %(VERY SLOW)
               drop(j)=true;
            end
        end
    end

end

A(drop,:)=[];  

函数makeindex

function [index]=makeindex(k)                                              %
total=2^k;                                                                 %
index=zeros(total,k);                                                      %                                                                       
for i=1:k                                                                  %
    ii=1;                                                                  %
    cc=1;                                                                  %
    c=total/(2^i);                                                         %
    while ii<=total                                                        %
        if cc <=c                                                          %
            index(ii,i)=1;                                                 %
            cc=cc+1;                                                       %
            ii=ii+1;                                                       %
        else                                                               %
            ii=ii+c;                                                       %
            cc=1;                                                          %
        end                                                                %
    end                                                                    %
end                                                                        %
                                                                           %
end     

1 个答案:

答案 0 :(得分:3)

这是我的解决方案,如果你想要的话:

A=zeros(n,2*n);
A(:,1)=1;
for i=2:2:n*2-1
    A(:,i-1)=circshift(A(:,i-1),[-1 0]);
    A(:,i)=A(:,i-1);
    A(end,i)=0;
    A(:,i+1)=A(:,i);
end
A(:,end-1)=circshift(A(:,end-1),[-1 0]);
A=A';

对于n = 10: 经过的时间是0.000976秒。

旧代码: 经过的时间是32.804602秒。

N = 15: 经过的时间是0.000866秒。

旧代码: ......还在计算...;)