[Rcpp-devel] Working with indicators in Armadillo

Dirk Eddelbuettel edd at debian.org
Sat Feb 23 22:12:54 CET 2013


On 23 February 2013 at 21:33, Simon Zehnder wrote:
| Dear Rcpp-Devels,
| 
| I try to write some code in C++, where S is a classification vector (arma::uvec) with entries in between 1 and K: 

Well, that was an incomplete and unreproducible example. At a minimum, try to
make them complete and provide example input.
 
|   1 arma::mat repS = arma::repmat(S, 1, K);
|   2 arma::mat compM = arma::ones(S.n_rows, K);
|   3 arma::rowvec par_post(K);
|   4
|   5 for(unsigned int k = 0; k < K; ++k) {
|   6               compM.col(k) = compM.col(k) * (k + 1);
|   7 }
|   8
|   9 arma::umat ind = (repS == compM);
| 10 par_post = sum(ind);
| 
| I get an error with this code: 
| 
| error: no match for ‘operator=’ in ‘par_post = arma::sum(const T1&, arma::uword, const typename arma::enable_if<(arma::is_arma_type<T1>::value == true)>::result*, const typename arma::enable_if<(arma::resolves_to_vector<T1>::value == false)>::result*) [with T1 = arma::Mat<unsigned int>; arma::uword = unsigned int; typename arma::enable_if<(arma::is_arma_type<T1>::value == true)>::result = int; typename arma::enable_if<(arma::resolves_to_vector<T1>::value == false)>::result = int](0u, 0u, 0u)’
| 
| I think the problem in line 10 is passing an arma::uvec object to an arma::rowvec (double) object. Has anybody an idea to make the code a little more elegant and especially: functional?

It works in the version below where I simply promote the vector to double by
multiply with 1.0 when sum() is called.  As you result is not int either,
that seems fine.

Dirk


#include <RcppArmadillo.h>

// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::rowvec foo(arma::mat S, unsigned int K) {
  arma::mat repS = arma::repmat(S, 1, K);
  arma::mat compM = arma::ones(S.n_rows, K);
  arma::rowvec par_post(K);
  
  for(unsigned int k = 0; k < K; ++k) {
    compM.col(k) = compM.col(k) * (k + 1);
  }

  arma::uvec ind = 1.0*(repS == compM);
  par_post = arma::sum(1.0*ind);
  return par_post;
}

| 
| 
| Best
| 
| Simon
| _______________________________________________
| Rcpp-devel mailing list
| Rcpp-devel at lists.r-forge.r-project.org
| https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel

-- 
Dirk Eddelbuettel | edd at debian.org | http://dirk.eddelbuettel.com  


More information about the Rcpp-devel mailing list