MATLAB中的相邻元素与数学公式

时间:2017-01-18 14:13:04

标签: algorithm matlab math combinatorics

我有一个N = {1,2,3,4集合n=4元素,可能的相邻组合是:

{empty set} {1} {2} {3} {4} {1,2} {2,3} {3,4} {1,2,3} {2,3,4} and {1,2,3,4}

所以总的可能组合是c = 11,可以用公式计算:

c=(n^2/2)+(n/2)+1

我可以使用A = n X c进行建模,如下所示,其元素可以表示为(n,c):

Matrix A

我试图在MATLAB中实现这一点,但由于我已对上述数学进行了硬编码,因此我的代码在n > 4的情况下无法扩展:

n=4;
c=((n^2)/2)+(n/2)+1;
A=zeros(n,c); 

for i=1:n 
    A(i,i+1)=1; 
end 

for i=1:n-1 
    A(i,n+i+1)=1;
    A(i+1,n+i+1)=1;
end 

for i=1:n-2 
    A(i,n+i+4)=1;
    A(i+1,n+i+4)=1;
    A(i+2,n+i+4)=1; 
end 

for i=1:n-3 
    A(i,n+i+6)=1;
    A(i+1,n+i+6)=1;
    A(i+2,n+i+6)=1;
    A(i+3,n+i+6)=1;
end

根据我上面的数学公式,是否有一个相对低复杂度的方法在MATLAB中使用 n 数量的 N 元素来转换这个问题?

1 个答案:

答案 0 :(得分:2)

解决这个问题的简单方法是在设置了第一个k位的情况下采用位模式,并将其向下移n - k次,将每个移位列向量保存到结果中。所以,从

开始
1
0
0
0

转移1,2和3次以获得

|1 0 0 0|
|0 1 0 0|
|0 0 1 0|
|0 0 0 1|

我们将circshift用来实现这一目标。

function A = adjcombs(n)
   c = (n^2 + n)/2 + 1;   % number of combinations
   A = zeros(n,c);        % preallocate output array 

   col_idx = 1;             % skip the first (all-zero) column 
   curr_col = zeros(n,1);   % column vector containing current combination
   for elem_count = 1:n
      curr_col(elem_count) = 1;   % add another element to our combination
      for shift_count = 0:(n - elem_count)
         col_idx = col_idx + 1;   % increment column index 
         % shift the current column and insert it at the proper index
         A(:,col_idx) = circshift(curr_col, shift_count);
      end
   end
end

使用n = 4 and 6调用函数:

>> A = adjcombs(4)
A =

   0   1   0   0   0   1   0   0   1   0   1
   0   0   1   0   0   1   1   0   1   1   1
   0   0   0   1   0   0   1   1   1   1   1
   0   0   0   0   1   0   0   1   0   1   1

>> A = adjcombs(6)
A =

   0   1   0   0   0   0   0   1   0   0   0   0   1   0   0   0   1   0   0   1   0   1
   0   0   1   0   0   0   0   1   1   0   0   0   1   1   0   0   1   1   0   1   1   1
   0   0   0   1   0   0   0   0   1   1   0   0   1   1   1   0   1   1   1   1   1   1
   0   0   0   0   1   0   0   0   0   1   1   0   0   1   1   1   1   1   1   1   1   1
   0   0   0   0   0   1   0   0   0   0   1   1   0   0   1   1   0   1   1   1   1   1
   0   0   0   0   0   0   1   0   0   0   0   1   0   0   0   1   0   0   1   0   1   1