Module #6 Doing Math in R Part 2

This week we continued to evaluate matrixes in R using two given matrix sets(A and B), a diagonal matrix (4, 1, 2, 3) and then create a copy of a given matrix.

1. Consider A=matrix(c(2,0,1,3), ncol=2) and B=matrix(c(5,2,4,-1), ncol=2).

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

[,1] [,2]
[1,] 2 1
[2,] 0 3
B <- matrix(c(5,2,4,-1), ncol=2)
B

[,1] [,2]
[1,] 5 4
[2,] 2 -1

R Code

a) Find A + B

add <- A + B
add

[,1] [,2]
[1,] 7 5
[2,] 2 2

R Code

b) Find A – B

substract <- A – B
substract

[,1] [,2]
[1,] -3 -3
[2,] -2 4

R Code

After playing around with different uses of diag(), I finally got #2:

2. Using the diag() function to build a matrix of size 4 with the following values in the diagonal 4,1,2,3.

m2 <-diag(x = c(4, 1, 2, 3), nrow=4, ncol=4, names = TRUE)
m2

[,1] [,2] [,3] [,4]
[1,] 4 0 0 0
[2,] 0 1 0 0
[3,] 0 0 2 0
[4,] 0 0 0 3

R Code

3. Generate the following matrix:

m3 <- diag(x = 3, nrow=5, ncol=5, names = TRUE)
m3[,1]<- 2
m3[1,]<- 1
diag(m3) <- 3
m3

[,1] [,2] [,3] [,4] [,5]
[1,] 3 1 1 1 1
[2,] 2 3 0 0 0
[3,] 2 0 3 0 0
[4,] 2 0 0 3 0
[5,] 2 0 0 0 3

R Code

Honestly, #3 was very difficult and I am not sure if I did it correctly but it matches the given matrix. But, I feel as though playing around with diag() function and matrix functions really helped me understand how they work. In my other class(data and text mining), I am given a data set and use the as.matrix() function but did not understand until this assignment what that function actually does.

I found this website super helpful: https://stat.ethz.ch/R-manual/R-devel/library/base/html/diag.html

Leave a comment

Design a site like this with WordPress.com
Get started