Matrix Addition
Learn matrix addition using R, Rcpp, Armadillo, and Eigen.
We'll cover the following
Addition is defined over matrices having the same dimensions.
Here, both and are matrices.
Matrix addition in R
In base R, the binary operator +
, executes the addition.
Let’s implement the following example:
A <- matrix(c(1, -3, 2, 5, 2, 2),ncol = 3,nrow = 2,byrow = TRUE)B <- matrix(c(1, 7, -5, 3, 8, 4),ncol = 3,nrow = 2,byrow = TRUE)R = A + B # Adding Matrices A and Bcat("Matrix A:\n")Acat("\nMatrix B:\n")Bcat("\nMatrix R:\n")R
In the code above, in line 13, we have computed the sum of matrices and in variable R
. We then print all three matrices in lines 16, 19, and 22, respectively.
Matrix addition algorithm
Implementing the addition operation is really simple. The algorithm performs the addition element by element, using two nested loops along the rows and the columns.
#include <Rcpp.h>using namespace Rcpp;// [[Rcpp::export]]NumericMatrix mat_add(NumericMatrix A, NumericMatrix B) {int m = A.nrow();int n = A.ncol();if (m != B.nrow() | n != B.ncol()) {stop("error: matrices dimensions do not match");}NumericMatrix R(m,n);int i = 0, j = 0;for (i = 0; i < m; i++) { // loop over rowsfor (j = 0; j < n; j++) { // loop over columnsR(i,j) = A(i,j) + B(i,j); // elementwise addition}}return(R);}
When we compare the matrix addition implementation with the results of the R addition, we can confirm that it is correct.
all.equal(mat_add(A, B), R)
# [1] TRUE
Matrix addition in Armadillo
Adding matrices using Armadillo is just as simple as it is in R.
#include <RcppArmadillo.h>// [[Rcpp::depends(RcppArmadillo)]]using namespace Rcpp;// [[Rcpp::export]]// performing matrix addition using thr Armadillo libraryarma::mat mat_add_A(arma::mat A, arma::mat B) {arma::mat R = A + B;return(R);}
By comparing the results of the matrix addition using Armadillo C++ library with the results of the R addition, we see that the results are correct.
all.equal(mat_add_A(A, B), R)
## [1] TRUE
Matrix addition in Eigen
Now, let’s look at matrix addition using the Eigen library, which is similar to R and Armadillo.
#include <RcppEigen.h>// [[Rcpp::depends(RcppEigen)]]using namespace Rcpp;using Eigen::MatrixXd;// [[Rcpp::export]]// performing matrix additon using the Eigen libraryMatrixXd mat_add_E(MatrixXd A, MatrixXd B) {MatrixXd R = A + B;return(R);}
We can see that our results are correct by comparing the matrix addition results using the Eigen C++ library with the results from using R.
all.equal(mat_add_E(A, B), R)
## [1] TRUE