【发布时间】:2015-10-20 18:08:01
【问题描述】:
我有一个二维矩阵A,它只包含二进制值:
A = [0 0
0 1
1 0
1 1];
我想创建一个函数来生成A 中值的所有可能配置。在这种情况下,configuration 一词对应于数据行中任何可能的值组合(即,成对的列、三元组等)。例如,在上面提供的数据的简单情况下,我希望函数返回:
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? -
A只是一个例子还是总是枚举所有二进制向量? -
因为
A的值不是0就是1,所以没有必要对A(:,1)==0和A(:,1)==1进行编码,这就是为什么我没有把它们放进去。A是只是一个例子——实际上所有的二元向量可能都不存在。 -
我很难看到
B是如何由A组成的。当然,如果您希望所有可能的配置都比B大很多吗? -
如果你更清楚地解释你想要什么,你会得到更多的帮助。我不清楚这种模式
标签: matlab matrix combinations