带有异或、非或的布尔乘法(使用特征矩阵库)

kei*_*uld 6 c++ matrix hamming-code eigen eigen3

我正在尝试实现汉明纠错码,为此我需要获取一个布尔向量(数据)并将其与布尔矩阵(汉明生成器矩阵)相乘,执行异或运算(而不是像 OR 那样) Eigen 的默认 bool 行为)。在这个简单的教程中可以找到我正在做的一个例子:http : //michael.dipperstein.com/hamming/

我不一定必须使用 Eigen,所以如果您有解决方案,请随时提出 Eigen 以外的其他建议。

因此,例如一些编译的 C++ 代码,但不能以正确的方式工作:

#include <Eigen/Dense>
#include <iostream>

using namespace std;
using namespace Eigen;

typedef Eigen::Matrix<bool, 4, 7> Matrix4by7Bool;
typedef Eigen::Matrix<bool, 1, 4> Vector4Bool;
int main()
{
Matrix4by7Bool gm;
gm << 0,1,1,1,0,0,0,
      1,0,1,0,1,0,0,
      1,1,0,0,0,1,0,
      1,1,1,0,0,0,1;

Vector4Bool dm;
dm << 1,0,1,0;

cout << dm * gm;
}
Run Code Online (Sandbox Code Playgroud)

当前结果: 1 1 1 1 0 1 0
但我需要: 1 0 1 1 0 1 0

不同之处在于默认行为是先进行乘法运算,然后对每次乘法进行 OR 运算。由于我需要 XOR 而不是 OR,想知道使用 Eigen 执行此操作的最佳方法是什么?

如果这没有意义,很高兴尝试详细说明。

顺便说一句,不确定这是否重要,但我正在使用 G++ 开发 MacBook Air。今天刚刚下载了 Eigen 所以它的概率是最新的 (eigen3)

谢谢你,
基思

更新:鉴于下面接受的解决方案,我想重新发布正确的代码作为人们的参考:

#include <Eigen/Dense>
#include <iostream>

using namespace std;
using namespace Eigen;

typedef Eigen::Array<bool, 4, 7> Array4by7Bool;
typedef Eigen::Array<bool, 4, 1> Array1by4Bool;

struct logical_xor {
  bool operator() (bool a, bool b) const
  {
    return a != b;
  }
};

int main()
{
  Array4by7Bool gm;
  gm << 0,1,1,1,0,0,0,
        1,0,1,0,1,0,0,
        1,1,0,0,0,1,0,
        1,1,1,0,0,0,1;

  Array1by4Bool dm;
  dm << 1,0,1,0;

  cout << "result: "  <<  (gm.colwise() * dm).colwise().redux(logical_xor()) << endl;
}
Run Code Online (Sandbox Code Playgroud)

gga*_*ael 5

您可以使用广播和部分减少来模拟 matrix_vector 产品:

struct logical_xor { bool operator(bool a, bool b) { return a != b; }
result = (gm.array().colwise() * dm.transpose().array()).colwise().redux(logical_xor());
Run Code Online (Sandbox Code Playgroud)

如果您将变量声明为 Array 并且 dm 已经是一个列数组,那么这可以简化为:

result = (gm.colwise() * dm).colwise().redux(logical_xor());
Run Code Online (Sandbox Code Playgroud)