所有可能的配置我有一個二維矩陣A
,其中只包含二進制值:產生MATLAB
A = [0 0
0 1
1 0
1 1];
我想創建,其產生A
值的所有可能的配置功能。在這種情況下,單詞配置對應於一行數據(即,列對,三元組等)內的值的任何可能的組合。例如,在以上提供的數據的簡單情況下,我想函數返回:
B = [ A(:,1)==1, ...
A(:,2)==1, ...
A(:,1)==0 & A(:,2)==0, ...
A(:,1)==0 & A(:,2)==1, ...
A(:,1)==1 & A(:,2)==0, ...
A(:,1)==1 & A(:,2)==1];
B =
0 0 1 0 0 0
0 1 0 1 0 0
1 0 0 0 1 0
1 1 0 0 0 1
然而,我想的功能能夠處理任意大小的矩陣。在3列矩陣的情況下,所產生的配置數量要大得多:
A = [ 0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1]
B = [A(:,1)==1, ...
A(:,2)==1, ...
A(:,3)==1, ...
A(:,1)==0 & A(:,2)==0, ...
A(:,1)==0 & A(:,2)==1, ...
A(:,1)==0 & A(:,3)==0, ...
A(:,1)==0 & A(:,3)==1, ...
A(:,1)==1 & A(:,2)==0, ...
A(:,1)==1 & A(:,2)==1, ...
A(:,1)==1 & A(:,3)==0, ...
A(:,1)==1 & A(:,3)==1, ...
A(:,2)==0 & A(:,3)==0, ...
A(:,2)==0 & A(:,3)==1, ...
A(:,2)==1 & A(:,3)==0, ...
A(:,2)==1 & A(:,3)==1, ...
A(:,1)==0 & A(:,2)==0 & A(:,3)==0, ...
A(:,1)==0 & A(:,2)==0 & A(:,3)==1, ...
A(:,1)==0 & A(:,2)==1 & A(:,3)==0, ...
A(:,1)==0 & A(:,2)==1 & A(:,3)==1, ...
A(:,1)==1 & A(:,2)==0 & A(:,3)==0, ...
A(:,1)==1 & A(:,2)==0 & A(:,3)==1, ...
A(:,1)==1 & A(:,2)==1 & A(:,3)==0, ...
A(:,1)==1 & A(:,2)==1 & A(:,3)==1]
這似乎是一個非常具有挑戰性的問題,所以我想知道如果SO社區有任何想法!
我目前使用這個[醜陋]功能。它依賴於從MATLAB文件交換的allcomb功能:
function [B] = allconfigs(A)
% some information about A
N = size(A,1);
D = size(A,2);
% set up storage
B = A==1;
% iterate over levels of dimensionality (pairs, triplets, etc)
% I==1 can be ignored, as it is equal to A.
% I==(D-1) can be ignored, as it is an identity matrix of size N
for I = 2:(D-1)
% get all possible values given dimensionality I
possiblevalues = cell(1,I);
for j = 1:I
possiblevalues{j} = [0 1];
end
possiblevalues = allcomb(possiblevalues{:});
npossible = size(possiblevalues,1);
% get all possible combinations of dimensions
combinations = combnk(1:D,I);
ncombs = size(combinations,1);
% check if the data under each dimension combination matches each value possibility
for J = 1:ncombs
dimensions = A(:,combinations(J,:));
for K = 1:npossible
matches = dimensions == repmat(possiblevalues(K,:),[N,1]);
matches = all(matches==1,2);
B = cat(2,B,matches);
end
end
end
% if I is the full set of data, the matches are an identity matrix.
B = cat(2,B,eye(N));
return
該函數返回正確的結果(但要注意,它產生的列不在相同的順序我輸入了)。它太醜了。有誰知道更優雅的東西?
我有一些理解模式的問題。爲什麼是'A(:1)== 0&A(:,2)== 0&A(:,3)== 0,'和A(:,1)== 0&A(:, 2)== 0'包含但不包含'A(:,1)== 0'? – Daniel
「A」僅僅是一個例子還是總是枚舉所有二進制向量? – Daniel
因爲'A'的值是0或1,所以不需要對'A(:,1)== 0'和'A(:,1)== 1'進行編碼,這就是爲什麼我跳過放在那裏。'A'只是一個例子 - 實際上所有的二進制向量可能不存在。 –