# [Rcpp-devel] Matrix rows/columns

Dirk Eddelbuettel edd at debian.org
Mon Dec 20 13:58:12 CET 2010

```Hi Cedric,

On 20 December 2010 at 11:11, Cedric Ginestet wrote:
| Dear Rcpp users and developers,
|
| I seem to be unable to understand how to extract a row/column from an
| Rcpp Matrix. Here are some reproducible codes:
|
| ###############################
| library(Rcpp);
| library(inline)
| src <- '
| IntegerMatrix D;
|    IntegerVector Drow = D.row(1);
| return Drow;
| '
| rowExtraction <-
| cxxfunction(signature(D="matrix"),body=src,plugin="Rcpp",verbose=TRUE)
| D <- matrix(1:9,3,3)
| rowExtraction(D)
| ################################
|
| Although this code compile, I get the following error when executing
| rowExtraction:
| Error in rowExtraction(D) : index out of bounds
|
| How can I extract a row into an Rcpp:vector?

You did it right, you just overlooked one small point: your matrix D was
empty! Hence the 'out of bounds' error. There was no connection between the
matrix D you created in R and the one you tried to operate on in C++.

Here I name the matrix passed in 'Dsexp' and construct D from it:

R> src <- '
+    IntegerMatrix D(Dsexp);
+    IntegerVector Drow = D.row(1);
+    return Drow;
+ '
R> rowExtraction <- cxxfunction(signature(Dsexp="matrix"),body=src,plugin="Rcpp")
R> D <- matrix(1:9,3,3)
R> rowExtraction(D)
[1] 2 5 8
R>

That gets you the second (!!) row as per the 0-based indexing in C and C++.

Dirk

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