3

What is the best way to perform modulus operator over a vector or matrix in c++ Armadillo?


The vector and matrix classes overload the % operator to perform element-wise multiplication. Trying to use it yields an invalid operands error. I was expecting that

uvec a = {0, 1, 2, 3};
uvec b = a % 2;
cout << "b" << endl;

would yield the following:

b:
    0
    1
    0
    1
Brian
  • 3,453
  • 2
  • 27
  • 39

1 Answers1

4

Operator '%' is for element-wise matrix multiplication. You have to create your own function:

/**
 * Extend division reminder to vectors
 *
 * @param   a       Dividend 
 * @param   n       Divisor
 */
template<typename T>
T mod(T a, int n)
{
    return a - floor(a/n)*n;
}   
cecconeurale
  • 108
  • 6
  • Nice idea---you should make note that it will require the use of `arma::floor` and specify that it requires armadillo vector types, not `std::vector`s. – Brian Jan 23 '15 at 00:15