Reputation: 37
When I want to run following cpp code
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
void print_mat(double *Mat, int nbLig, int nbCol) {
int i, j;
for (i = 0; i < nbLig; i++) {
for (j = 0; j < nbCol; j++)
printf("%f ", *(Mat + (nbCol * i) + j));
putchar('\n');
}
}
By Rcpp and sourceCpp command
I see
cannot convert 'Rcpp::traits::input_parameter::type {aka Rcpp::InputParameter}' to 'double*' for argument '1' to 'void print_mat(double*, int, int)' print_mat(*Mat, nbLig, nbCol)
How remove this error
Upvotes: 2
Views: 1038
Reputation: 368499
Briefly:
Rprintf()
to print per Writing R ExtensionsHence a need for a repaired version:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
void print_mat(NumericMatrix Mat) {
int nbLig = Mat.nrow(), nbCol = Mat.ncol();
int i, j;
for (i = 0; i < nbLig; i++) {
for (j = 0; j < nbCol; j++)
Rprintf("%f ", Mat(i,j));
Rprintf("\n");
}
}
/*** R
print_mat(matrix(1:9,3))
*/
where I also included an example use. Pulling that into R yields
R> sourceCpp("/tmp/foomat.cpp")
R> print_mat(matrix(1:9,3))
1.000000 4.000000 7.000000
2.000000 5.000000 8.000000
3.000000 6.000000 9.000000
R>
Needless to say, you could also get this via a single command:
// [[Rcpp::export]]
void print_mat2(NumericMatrix Mat) {
print(Mat);
}
which give you row and column headers as in R:
R> print_mat2(matrix(1:9,3))
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
R>
Upvotes: 4