Reputation: 426
In my function, I want to compare the rows in a matrix by use ==,but it doesn't work.
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
// [[Rcpp::export]]
double accept(arma::mat x){
int b=x.n_rows;
arma::vec B(b-1);B.zeros();
for(int i=0;i<b-1;i++){
arma::rowvec a1;arma::rowvec a2;
if(x.row(i)==x.row(i+1)){
B[i]=0;
}else{
B[i]=1;
}
}
double bb;bb=sum(B)/(b-1);
return(bb);
}
Error message:
c:/Rtools/mingw_64/bin/g++ -std=gnu++11 -I"C:/Users/songxl/DOCUME~1/R/R-35~1.0RC/include" -DNDEBUG -I../inst/include -fopenmp -I"C:/Users/songxl/Documents/R/R-3.5.0rc/library/Rcpp/include" -I"C:/Users/songxl/Documents/R/R-3.5.0rc/library/RcppArmadillo/include" -I"E:/adptive/block" -O2 -Wall -mtune=generic -c acp.cpp -o acp.o acp.cpp: In function 'double accept(arma::mat)': acp.cpp:10:16: error: could not convert 'arma::operator==(const T1&, const T2&) [with T1 = arma::subview_row; T2 = arma::subview_row; typename arma::enable_if2<(arma::is_arma_type::value && arma::is_arma_type::value), const arma::mtGlue >::result = const arma::mtGlue, arma::subview_row, arma::glue_rel_eq>](((const arma::subview_row)(& arma::Mat::row(arma::uword) [with eT = double; arma::uword = unsigned int](((arma::uword)(i + 1))))))' from 'arma::enable_if2, arma::subview_row, arma::glue_rel_eq> >::result {aka const arma::mtGlue, arma::subview_row, arma::glue_rel_eq>}' to 'bool' if(x.row(i)==x.row(i+1)){ ^ make: *** [acp.o] Error 1
Upvotes: 0
Views: 1584
Reputation: 20746
Instead of using Dirk's reduction technique, I would recommend using the built in arma::approx_equal() function as eluded to by @mtall.
The idea here is to check to see if the values are within an epsilon neighborhood defined by a tolerance. For example, let scalars x
and y
be considered equal if |x − y| ≤ tol
.
Sample implementation
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
double accept(arma::mat x){
int b = x.n_rows;
arma::vec B = arma::zeros<arma::vec>(b-1);
for(int i = 0; i < b - 1; ++i){
bool same_vec = approx_equal(x.row(i), x.row(i+1), "absdiff", 0.002);
if(same_vec) {
B[i] = 0;
} else {
B[i] = 1;
}
}
double bb = sum(B)/(b-1);
return bb;
}
Test:
x = matrix(rep(1:10, 2), ncol = 2)
accept(x)
# [1] 1
Upvotes: 2
Reputation: 368231
It looks like the equality comparison does not work. (There is a whole long story on why that is difficult for floating point anyway, see what every computer scientist should know about floating point.)
So I rewrote it as sum(abs(diff(a1,a2))) < eps
; feel free to use a different value of epsilon:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
// [[Rcpp::export]]
double accept(arma::mat x){
int b = x.n_rows;
arma::vec B(b-1);
B.zeros();
for (int i=0;i<b-1;i++){
arma::rowvec a1 = x.row(i);
arma::rowvec a2 = x.row(i+1);
if (sum(abs(a1-a2)) < 1e-8) {
B[i]=0;
}else{
B[i]=1;
}
}
double bb = sum(B) / (b-1);
return(bb);
}
Otherwise you were very close.
Upvotes: 1