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:
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.
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.
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.
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