如果你没有太多变量,你可以很容易地做到这一点。
如果您确实有很多变量,此方法将停止运行,因为它使用 size 的矩阵K*(2^K),其中K是变量的数量,并且combvec对于较大的变量也很慢K。
虽然您必须警惕变量的数量,但这种方法非常有能力以很少的开销处理许多逻辑“方程式”。
在x, y,z示例中:
% Get all combinations of x/y/z, where each is true or false
opts = repmat( {[true, false]}, 1, 3 );
xyz = combvec( opts{:} )
% Assign each row to a named variable
x = xyz(1,:); y = xyz(2,:); z = xyz(3,:);
% Get the combinations which satisfy your conditions
results = xyz( :, (x & y) & (x | z) );
% Each column of results is a solution
>> results
results =
1 1
1 1
1 0
写得更笼统,它可能看起来像这样:
K = 3; % K variables (previously x, y and z so K = 3)
% Create all true/false combinations
opts = repmat( {[true, false]}, 1, K );
combs = combvec( opts{:} );
% Shorthand so we can write in(i) not combs(i,:)
in = @(k) combs(k,:);
% Apply conditions
results = combs( :, (in(1) & in(2)) ...
& (in(1) | in(3)) );
注意:如果您没有神经网络工具箱,您将没有combvec. 获得所有组合有很多选择。