--- title: "14 - Linear Algebra" output: litedown::html_format: options: toc: true number_sections: true vignette: > %\VignetteIndexEntry{14 - Linear Algebra} %\VignetteEngine{litedown::vignette} %\VignetteEncoding{UTF-8} editor: markdown: wrap: sentence bibliography: ["references.bib"] --- ## Motivation R provides out-of-box support for matrices and vectors. This is not the case for C++ code, where you need to use a library such as [Armadillo](https://arma.sourceforge.net/) that has a wrapper for R [@vargassepulveda25]. One of the nicest Armadillo features is that it has a similar syntax to MATLAB. ## Using Armadillo [cpp11armadillo](https://pacha.dev/cpp11armadillo/) provides a detailed R-specific documentation with worked examples. Because the examples in the cpp11armadillo are self-contained and with detailed explanations, this vignette will not repeat them here. Here is one of the over five-hundred examples from the cpp11armadillo package to compute $\hat{\beta} = (X^TX)^{-1}X^Ty$ for a linear model using the cpp4r concepts already covered: ```cpp Mat ols_(const doubles_matrix<>& y, const doubles_matrix<>& x) { Mat Y = as_Mat(y); // Col Y = as_Col(y); also works Mat X = as_Mat(x); Mat XtX = X.t() * X; // X'X Mat XtX_inv = inv(XtX); // (X'X)^(-1) Mat beta = XtX_inv * X.t() * Y; // (X'X)^(-1)(X'Y) return beta; } [[cpp4r::register]] doubles_matrix<> ols_mat_(const doubles_matrix<>& y, const doubles_matrix<>& x) { Mat beta = ols_(y, x); return as_doubles_matrix(beta); } [[cpp4r::register]] doubles ols_dbl_(const doubles_matrix<>& y, const doubles_matrix<>& x) { Mat beta = ols_(y, x); return as_doubles(beta); } ``` One of the advantages of cpp11armadillo is that it connects cpp11 (and cpp4r) with Armadillo, allowing you to use the `as_Mat()` and `as_doubles_matrix()` functions as the "bread" of the sandwich, where pure Armadillo code serves as the "meat". ## References