繁体   English   中英

具有数学公式的MATLAB中的相邻元素

[英]Adjacent Elements in MATLAB with Mathematical Formulation

我有一套 N = {1,2,3,4 n = 4的 元素及其可能的相邻组合为:

{空集} {1} {2} {3} {4} {1,2} {2,3} {3,4} {1,2,3} {2,3,4}和{1,2 ,3,4}

因此,可能的总组合为c = 11,可以使用以下公式计算:

C =(N ^ 2/2)+(N / 2)+1

我可以使用 A = n X c 如下所示,其元素可以表示为a(n,c)是:

矩阵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

按照我上面的数学公式,是否存在相对低复杂度的方法来在具有n个元素集N的元素中的MATLAB中转换此问题?

进行此操作的简单方法是采用设置了前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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM