What are NumericMatrix and LogicalMatrix in Rcpp?

Overview

NumericMatrix and LogicalMatrix are two of the many matrix classes for different data types provided by R in Rcpp.

Rcpp is a package that integrates R and C++. It provides both R functions and C++ classes.

NumericMatrix

The NumericMatrix is a type of matrix that takes a numerical vector value as a parameter, and the elements in it are double.

Example

Let’s discuss this with a code example below:

main.r
main.cpp
Rcpp::sourceCpp('/usercode/main.cpp')
myNumericMatrix()

Explanation

The code above is for the NumericMatrix, where the elements of the matrix are numerical values.

  • Line 1: We include the Rcpp library.
  • Line 4: We export Rcpp into this code file.
  • Line 5: We add the function header.
  • Line 7: We create a matrix of 3 columns and 3 rows. We initialize them with a 0 value, which is a double data type in C++. By default, it initializes the matrix with all 0 entries.
  • Line 8: We return the created matrix.

LogicalMatrix

On the other hand, we have LogicalMatrix. In LogicalMatrix, the function gets a logical vector where the elements are of the bool data type.

Example

Let’s discuss this in detail with the code example below.

main.r
main.cpp
Rcpp::sourceCpp('/usercode/main.cpp')
myLogicalMatrix()

Explanation

The code given above is for the LogicalMatrix, where the elements of the matrix are logical values.

  • Line 1: We include the Rcpp library.
  • Line 4: We export Rcpp into this code file.
  • Line 5: We add the function header.
  • Line 7: We create a matrix of 3 columns and 3 rows. We initialize them with a FALSE value which is of the bool data type. By default, it initializes the matrix with all FALSE entries.
  • Line 8: We return the created matrix.

Note: There are two files in our code. One is an .r file named main.r, and the other one is a .cpp file named main.cpp. The major part of code is written in the .cpp file, while the .r file calls the function. Both the files are mutually integrated with each other using sourceCpp.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved