logo

Calculating the Product, Inverse, and Transpose of a Matrix in R 📂R

Calculating the Product, Inverse, and Transpose of a Matrix in R

Overview

The strengths of R lie in the simple manipulation of various datasets, including matrices, and the provision of a wealth of free statistical packages. It’s obvious, but the computation of matrices in statistical analysis is very important, and R excellently fulfills these needs. Unless it’s MATLAB or Julia, in other languages, you’ll have to annoyingly define the operations on matrices separately.

Code

Matrix Multiplication

For example, let’s say we want to switch rows $2$ and $3$ of matrix $a = \begin{bmatrix} 2 & 1 & 0 \\ 1 & 2 & 1 \\ 0 & 1 & 2 \end{bmatrix}$. In linear algebra, multiplying the permutation matrix $P = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 0 & 1 \\ 0 & 1 & 0 \end{bmatrix}$ to the left of $A$ will give the desired result. In other words, $PA = \begin{bmatrix} 2 & 1 & 0 \\ 0 & 1 & 2 \\ 1 & 2 & 1 \end{bmatrix}$. Let’s implement this calculation in R using the matrix multiplication operator %*%.

A = matrix(c(2,1,0,1,2,1,0,1,2),ncol=3); A
P = matrix(c(1,0,0,0,0,1,0,1,0),ncol=3); P
P%*%A

The result of running the above code is as follows.

20171111\_155934.png

Inverse and Transpose Matrices

It can be verified that this matches the theoretical calculation exactly. Let’s define the obtained matrix as $B$ and continue to find the inverse and transpose matrices.

B=P%*%A; B
solve(B)
t(B)

The function for finding the inverse matrix is solve(), and the function for finding the transpose matrix is t(). It’s easy to guess that t() came from Transpose. On the other hand, the reason why the inverse is defined as solve() instead of inverse() is because, given a system of equations $A \mathbf{x} = \mathbf{b}$, the solution is given by $\mathbf{x} = A ^{-1} \mathbf{b}$. Finding the inverse is tantamount to solving the problem.

The result of running the above code is as follows.

20171111\_161122.png

The transpose matrix is simply a matter of reversing rows and columns, so the result can be seen at a glance. The inverse matrix was calculated as $$ B^{-1} = \begin{bmatrix} {{3}\over{4}} & {{1}\over{4}} & -{{1}\over{2}} \\ -{{1}\over{2}} & -{{1}\over{2}} & 1 \\ {{1}\over{4}} & {{3}\over{4}} & -{{1}\over{2}} \end{bmatrix} = {{1}\over {4}} \begin{bmatrix} 3 & 1 & -2 \\ -2 & -2 & 4 \\ 1 & 3 & -2 \end{bmatrix} $$ , but since it’s difficult to derive it by ourselves, let’s just check the result. $$ B^{-1} B = {{1}\over {4}} \begin{bmatrix} 3 & 1 & -2 \\ -2 & -2 & 4 \\ 1 & 3 & -2 \end{bmatrix} \begin{bmatrix} 2 & 1 & 0 \\ 0 & 1 & 2 \\ 1 & 2 & 1 \end{bmatrix} = {{1}\over {4}} \begin{bmatrix} 4 & 0 & 0 \\ 0 & 4 & 0 \\ 0 & 0 & 4 \end{bmatrix} = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix} $$