簡體   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