Search code examples
c++armadillo

How to do bit-wise AND between multi-dimensional arrays using armadillo in C++?


My task is to rewrite the codes is_valid = (DoG == DoG_max) & (DoG >= threshold); in matlab using armadillo with C++. The DoG and DoG_max are multidimensional arrays with the same size 907 x 1210 x 5, and the threshold is a scalar.

According to the documentation of armadillo, the bit-wise equal operator == is built-in and the bit-wise greater than operation can be replaced with the member function .clean() which is to set all elements but the ones higher than the threshold to zeros.

Here is my codes:

// 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));
}

What confuses me is the bit-wise AND operator, which is not provided by armadillo. I want to know whether the logic of my codes is consistent with is_valid = (DoG == DoG_max) & (DoG >= threshold);? Based on my investigation, the result is different to that in matlab.

If there're solutions using Eigen, please also tell me!


Solution

  • The && operator is implemented in Armadillo, but strangely it's not documented. Try this as a translation of your Matlab code:

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

    In case you want a scalar output, try this:

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

    There is some confusion in the meaning of "&" and "&&" between C++ and Matlab. In C++, "&" means "bitwise AND", while "&&" means "logical AND". https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

    In Matlab, "&" and "&&" both mean "logical AND", but have slightly different evaluation depending on the context: What's the difference between & and && in MATLAB?