ndgrid非常多你的朋友在這裏:
function t = truthTable(n)
dims = repmat({[false, true]}, 1, n);
[grids{1:n}] = ndgrid(dims{:});
grids = cellfun(@(g)g(:), grids, 'UniformOutput',false);
t = [grids{:}];
首先,你需要創建網格的真值表中的維數。一旦你有了這些,你可以列出它們來獲得你需要的列向量,你可以水平連接這些列向量來得到你的真值表。
我想這將是非常有競爭力的表現。
>> truthTable(2)
ans =
0 0
1 0
0 1
1 1
>> truthTable(4)
ans =
0 0 0 0
1 0 0 0
0 1 0 0
1 1 0 0
0 0 1 0
1 0 1 0
0 1 1 0
1 1 1 0
0 0 0 1
1 0 0 1
0 1 0 1
1 1 0 1
0 0 1 1
1 0 1 1
0 1 1 1
1 1 1 1
>>
>> timeit(@() truthTable(20))
ans =
0.030922626777
編輯:使用重塑,而不是列提領了進一步的性能改進
function t = truthTable(n)
dims = repmat({[false, true]}, 1, n);
[grids{1:n}] = ndgrid(dims{:});
grids = cellfun(@(g) reshape(g,[],1), grids, 'UniformOutput',false);
t = [grids{:}];
>> timeit(@() truthTable(20))
ans =
0.016237298777