在 MatLab 中生成真值 table

Generate truth table in MatLab

我想在 MatLab 中用 i 列和 i2 行创建一个真理 table。例如,如果 i=2,则

T = 
[0  0] 
[1  0] 
[0  1] 
[1  1]

已经创建了执行此操作的代码here

这是一个较大项目的一部分,需要很大的空间。效率是一个问题。有没有更高效的代码来创造一个真相table? MatLab 是否有内置函数来执行此操作?

编辑:对格式感到抱歉!

是这样的吗?

n=2;
d=[0:2^n-1].';

T=dec2bin(d,n)

T =

00
01
10
11

dec2bin 将为您提供一个字符数组,如果需要,您可以将其转换为逻辑数组。还有de2bi直接给你一个数值数组,但是你需要更新版本的Matlab并且位的顺序是相反的。


这里是 Luis Mendo's 加速,它复制了 dec2binnd 同上):

T=rem(floor(d*pow2(1-n:0)),2);

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{:}];

首先,您需要为真实的维数创建网格 table。一旦你有了这些,你就可以将它们列化以获得你需要的列向量,你可以水平连接这些列向量以获得你的真相 table。

我想这个性能会很有竞争力。

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

我知道这个问题已经死了一段时间了,但我也在想同样的事情,并找到了一个我非常喜欢的解决方案。想在这里分享它:

fullfact(ones(1, i) + 1) - 1