# Matrix in Rcpp & RcppArmadillo Packages in R (2 Examples)

You want to know how to define matrices in the Rcpp package in R? We show you how, both with standard Rcpp and RcppArmadillo. In the examples, we create matrices from scratch and fill them with vector values. For those who are new to Rcpp: Check out our Rcpp post and RcppArmadillo post first.

We structure this post as follows:

Off we go.

## Example 1: Standard Rcpp Matrix

Load the Rcpp package.

if (!require('Rcpp', quietly = TRUE)) { install.packages('Rcpp') } library('Rcpp') # Load package 'Rcpp'

First, let us define a function “f_mat_empty” which creates an empty matrix (i.e. all entries are 0) with given dimension.

cppFunction(' Rcpp::NumericMatrix f_mat_empty( Rcpp::NumericVector dim_mat ) { // Create an empty matrix with dimensions dim_mat return Rcpp::NumericMatrix(dim_mat[0], dim_mat[1]); } ')

Test the function:

f_mat_empty(c(3,2)) # [,1] [,2] # [1,] 0 0 # [2,] 0 0 # [3,] 0 0

Now, for creating a matrix with certain values, we can first create an empty matrix and then fill its entries with *std::copy()*. As an example, we define a function called “f_mat_runif” which creates a matrix of given dimension and fills its entries with random normally distributed values.

cppFunction(' Rcpp::NumericMatrix f_mat_rnorm( Rcpp::NumericVector dim_mat ) { // Create an empty matrix with dimensions dim_mat Rcpp::NumericMatrix Mat(dim_mat[0], dim_mat[1]); // Draw random normally distributed values and store them in vector "vals" Rcpp::NumericVector vals = rnorm(dim_mat[0] * dim_mat[1]); // Fill matrix "Mat" by values of vector "vals" std::copy(vals.begin(), vals.end(), Mat.begin()); return Mat; } ')

Test the function:

set.seed(9) f_mat_rnorm(c(3,2)) # [,1] [,2] # [1,] -0.7667960 -0.2776050 # [2,] -0.8164583 0.4363069 # [3,] -0.1415352 -1.1868725

## Example 2: RcppArmadillo Matrix

Just like in standard Rcpp, we can also program both functions in RcppArmadillo. Why would we care about **RcppArmadillo**? RcppArmadillo integrates the Armadillo C++ library into R. It is great for linear algebra and has a rather straightforward syntax. Take a look at our blog post about it here. A documentation of the Armadillo functions and classes can be found here.

cppFunction(depends = "RcppArmadillo", ' arma::mat f_arma_mat_empty( arma::vec dim_mat ) { // Create an empty matrix with dimensions dim_mat return arma::mat(dim_mat[0], dim_mat[1]); } ')

You see that we explicitly have to call the RcppArmadillo package in *cppFunction()*. Test the function:

f_arma_mat_empty(c(3,2)) # [,1] [,2] # [1,] 0 0 # [2,] 0 0 # [3,] 0 0

Next, a matrix with random normally distributed values:

cppFunction(depends = "RcppArmadillo", ' arma::mat f_arma_mat_rnorm( arma::vec dim_mat ) { // Create a matrix with dimensions dim_mat, // filled with random normally distributed values return arma::mat(dim_mat[0], dim_mat[1], arma::fill::randn); } ')

Whenever you create an object and use *arma::fill::randn*, all entries are filled by random normally distributed values. Test the function:

set.seed(9) f_arma_mat_rnorm(c(3,2)) # [,1] [,2] # [1,] -0.6465762 -1.083608 # [2,] -0.6275584 -1.331588 # [3,] -0.1666509 -1.591494

Careful: You see that although we set the same seed, functions *f_arma_mat_rnorm()* and *f_mat_rnorm()* do not return the same random values.

## Video & Further Resources

We give you a general overview of the Rcpp package and its advantages for your R code here. For more information on C++ and the random numbers generated above, you might want to look into the following YouTube video titled “I just wanted a random integer” by Cheinan Marks, uploaded by the CppCon channel.

**Please accept YouTube cookies to play this video.** By accepting you will be accessing content from YouTube, a service provided by an external third party.

If you accept this notice, your choice will be saved and the page will refresh.

On https://statisticsglobe.com/, we have many more tutorials which could be of interest to you:

- sugar Functions in Rcpp Package in R (Example)
- Construct 3D Array in Rcpp Package in R (2 Examples)
- RcppArmadillo Package in R (Example)
- R programming Overview

This post showed you different ways of constructing a Rcpp matrix in R. We would love to hear your comments and questions below.

This page was created in collaboration with Anna-Lena Wölwer. Have a look at Anna-Lena’s author page to get more information about her academic background and the other articles she has written for Statistics Globe.

### Statistics Globe Newsletter