首页 > 解决方案 > 如何在 C++ 中使用犰狳在多维数组之间进行按位与?

问题描述

我的任务是使用带有 C++ 的犰狳重写is_valid = (DoG == DoG_max) & (DoG >= threshold);matlab 中的代码。DoG和是大小相同的DoG_max多维数组907 x 1210 x 5,而threshold is a scalar.

根据armadillo的文档,按位等于运算符是内置的,按位大于运算可以替换为成员函数,该成员函数将除高于阈值的元素之外的所有元素设置为零。 == .clean()

这是我的代码:

// arma::cube DoG, DoG_max;  // Size: 907 x 1210 x 5.
arma::ucube is_valid(arma::size(DoG), arma::fill::zeros);
DoG.clean(threshold);
for (int s = 0; s < is_valid.n_slices; ++s) {
  is_valid.slice(s) = (DoG.slice(s) == DoG_max.slice(s));
}

让我感到困惑的是按位与运算符,它不是犰狳提供的。我想知道我的代码逻辑是否符合 is_valid = (DoG == DoG_max) & (DoG >= threshold);?根据我的调查,结果与matlab中的不同。

如果有使用 Eigen 的解决方案,也请告诉我!

标签: c++armadillo

解决方案


&&运算符是在 Armadillo 中实现的,但奇怪的是它没有记录在案。试试这个作为你的 Matlab 代码的翻译:

ucube is_valid = (DoG == DoG_max) && (DoG >= threshold);

如果你想要一个标量输出,试试这个:

bool is_valid = all(vectorise((DoG == DoG_max) && (DoG >= threshold)));

C++和Matlab之间的“&”和“&&”的含义有些混淆。在 C++ 中,“&”表示“按位与”,而“&&”表示“逻辑与”。 https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

在 Matlab 中,“&”和“&&”都表示“逻辑与”,但根据上下文的不同,计算结果略有不同:MATLAB 中的 & 和 && 有什么区别?


推荐阅读