title: How can I replicate R's functionality with multiplying a matrix by a vector element-wise in Rcpp or Armadillo?
body: <p>In R, multiplying a matrix by a vector is element-wise by default, and works like this:</p>
  <pre><code>A &lt;- matrix(c(1,2,3,4,5,6), nrow=2)
  b &lt;- c(1,3)
  A * b
       [,1] [,2] [,3]
  [1,]    1    3    5
  [2,]    6   12   18
  </code></pre>
  <p>Essentially, each element of the matrix is multiplied by an element of the vector round-robin. I want to recreate this functionality in C++, using Rcpp or its extensions like RcppEigen or RcppArmadillo.</p>
  <p>With Armadillo, I've tried the following:</p>
  <pre><code>arma::mat X ;
  arma::vec beta ;
  
  beta.resize ( 2 ) ;
  
  beta (0) = 1.0 ;
  beta (1) = 3.0 ;
  
  X.resize ( 3, 2 ) ;
  
  X (0,0) = 1.0 ;
  X (0,1) = 2.0 ;
  X (1,0) = 3.0 ;
  X (1,1) = 4.0 ;
  X (2,0) = 5.0 ;
  X (2,1) = 6.0 ;
  
  Rcout &lt;&lt; X * beta &lt;&lt; std::endl ;
  </code></pre>
  <p>Which results in a vector: [7, 15, 23], as if this were matrix multiplication. Substituting the <code>*</code> with a <code>%</code> for element-wise multiplication results in an error: &quot;error: element-wise multiplication: incompatible matrix dimensions: 3x2 and 2x1&quot;</p>
  <p>Is there any built-in function for this R-like behavior, or will I need to create my own function (which I have, but I'd prefer an &quot;official&quot; way of doing it)</p>
  <pre><code>NumericMatrix matrixTimesVector(NumericMatrix mat, NumericVector vec){
      NumericMatrix res(mat.rows(), mat.cols());
      int index = 0;
      for (int i = 0; i &lt; mat.cols(); ++i){
          for (int j = 0; j &lt; mat.rows(); ++j){
              res( j , i ) = mat( j , i ) * vec[index++ % vec.size()];
          }
      }
      return res;
  }
  </code></pre>