translating R's %in% to C++ -


i trying translate piece of r code c++ (via rcpp) uses %in% operator. know rcpp has sugar in(), don't understand how relates. there so question regarding %in% couldn't sort out how 1 relates too. rcpp gallery wonderful when search in() don't find posts.

here simple example of problem. suppose want create identity matrix constrain elements on diagonal zero. (this no longer identity matrix understand mean.) can in r function this:

r_eye <- function(n, v) {   <- matrix(data = 0, nrow = n, ncol = n)   for(i in 1:n) {     for(j in 1:n) {       if(i==j & !(i %in% v)) {         a[i,j] <- 1       }     }   }   return(a) } 

where n integer determines size of square matrix , v integer vector of "constraints". starting matrix of zeros, loop on rows , columns. if row equals column, , if row not among constraints, assign value 1 matrix entry. instance, if run r_eye(n=6, v=c(1,2,3)), "identity" matrix first 3 diagonal elements 0 , remaining one:

> r_eye(n = 6, v = c(1,2,3))      [,1] [,2] [,3] [,4] [,5] [,6] [1,]    0    0    0    0    0    0 [2,]    0    0    0    0    0    0 [3,]    0    0    0    0    0    0 [4,]    0    0    0    1    0    0 [5,]    0    0    0    0    1    0 [6,]    0    0    0    0    0    1 

the bottleneck translating c++ second part of "if" condition: !(i %in% v). can create identity matrix

#include <rcpp.h> using namespace rcpp;  // [[rcpp::export]] numericmatrix cpp_eye(int n) {   numericmatrix a(n,n);   for(int = 0; <= n; i++) {     for(int j = 0; j <= n; j++) {       if(i==j) {           a(i,j) = 1;         }        }     }   return a; } 

but possible squeeze in second "if" condition r function does? or have consider different approach?

as far find out, r vector passed rcpp::numericvector, provides begin() , end() std::vector. try this:

#include <algorithm>  bool in(int value, const numericvector & vec) {     return vec.end() != std::find(vec.begin(), vec.end(), value); }   numericmatrix cpp_eye(int n, numericvector v) {     numericmatrix a(n,n);     for(int = 0; <= n; i++) {         for(int j = 0; j <= n; j++) {             if((i==j) && in(i, v)) {                a(i,j) = 1;             }          }     }     return a; } 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -