Module # 6 Doing math in R part 2

 



Doing Math in R: Part 2


In this blog post, we'll delve into some matrix operations and matrix generation in R. We'll use basic functions and operations to manipulate matrices and create new ones based on specific requirements.


1. Matrix Operations


Consider two matrices:


\( A = \begin{pmatrix} 2 & 0 \\ 1 & 3 \end{pmatrix} \) and \( B = \begin{pmatrix} 5 & 2 \\ 4 & -1 \end{pmatrix} \)


(a) Addition:

To find the sum of matrices \( A \) and \( B \), we'll use the `+` operator in R.


```R

A <- matrix(c(2, 0, 1, 3), ncol = 2)

B <- matrix(c(5, 2, 4, -1), ncol = 2)


A + B

```


The result of \( A + B \) is:


\( \begin{pmatrix} 2+5 & 0+2 \\ 1+4 & 3+(-1) \end{pmatrix} = \begin{pmatrix} 7 & 2 \\ 5 & 2 \end{pmatrix} \)


(b) Subtraction:

To find the difference between matrices \( A \) and \( B \), we'll use the `-` operator in R.


```R

A - B

```


The result of \( A - B \) is:


\( \begin{pmatrix} 2-5 & 0-2 \\ 1-4 & 3-(-1) \end{pmatrix} = \begin{pmatrix} -3 & -2 \\ -3 & 4 \end{pmatrix} \)


2. Using diag() Function


We'll use the `diag()` function to create a diagonal matrix of size 4 with the values 4, 1, 2, and 3 on the diagonal.


```R

diag_matrix <- diag(c(4, 1, 2, 3))

diag_matrix

```


The resulting diagonal matrix is:


\( \begin{pmatrix} 4 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 2 & 0 \\ 0 & 0 & 0 & 3 \end{pmatrix} \)


**3. Generating a Specific Matrix**


We'll use the `diag()` function to generate the following matrix:


\[

\begin{pmatrix}

3 & 1 & 1 & 1 & 1 \\

2 & 3 & 0 & 0 & 0 \\

2 & 0 & 3 & 0 & 0 \\

2 & 0 & 0 & 3 & 0 \\

2 & 0 & 0 & 0 & 3 \\

\end{pmatrix}

\]


```R

specific_matrix <- diag(3, 5) + diag(1, 4) + diag(2, 3)

specific_matrix

```


The resulting matrix matches the specified pattern:


\[

\begin{pmatrix}

3 & 1 & 1 & 1 & 1 \\

2 & 3 & 0 & 0 & 0 \\

2 & 0 & 3 & 0 & 0 \\

2 & 0 & 0 & 3 & 0 \\

2 & 0 & 0 & 0 & 3 \\

\end{pmatrix}

\]



References


Wickham, H. (2015) R Packages: Organize, Test, Document and Share Your Code. Chapters 2-3.

Norman, M. (2011) The Art of R Programming. Chapters 9-10.

Comments