我有两个 Eigen VectorXi,包含 0 和 1。
VectorXi X;
X << 0, 1,1,1,1,0,0,1,0;
VectorXi Y;
Y << 1, 0,1,1,0,0,1,1,0;
我想通过逐元素 bool AND 和 OR 来获取两个数组的并集和交集中的元素数量。
在 Matlab 中,这对应于:
x = [0,1,1,1,1,0,0,1,0];
y = [1,0,1,1,0,0,1,1,0];
sum(x & y)
sum(x | y)
但我不明白如何在 Eigen 中没有 for 循环的情况下做到这一点。像这样的东西:
X.array() | Y.array()
不起作用。
一些想法?
为什么只有普通操作才实现为 cwise
操作?
最佳答案
对于这种特殊情况,您可以使用
X.cwiseProduct(Y)
(X + Y).cwiseMin(1)
这取决于元素仅为 0 和 1。更一般地,您可以定义自定义二进制仿函数:
struct BinaryOr {
typedef int result_type;
int operator()(int a, int b) const { return a | b; }
};
struct BinaryAnd {
typedef int result_type;
int operator()(int a, int b) const { return a & b; }
};
并使用
X.binaryExpr(Y, BinaryOr())
X.binaryExpr(Y, BinaryAnd())
关于c++ - 如何计算 Eigen VectorXi 中交集和并集的元素数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27544900/