Module # 6 Doing math in R part 2
Answer the following questions and post your answer on your blog:
1. Consider A=matrix(c(2,0,1,3), ncol=2) and B=matrix(c(5,2,4,-1), ncol=2).
a) Find A + B
b) Find A - B
2. Using the diag() function to build a matrix of size 4 with the following values in the diagonal 4,1,2,3.
3. Generate the following matrix:
## [,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
> # -----------------------------
> # Question 1: Matrix operations
>
> A <- matrix(c(2, 0, 1, 3), ncol = 2)
> B <- matrix(c(5, 2, 4, -1), ncol = 2)
>
> A
[,1] [,2]
[1,] 2 1
[2,] 0 3
> B
[,1] [,2]
[1,] 5 4
[2,] 2 -1
>
> # a) A + B
> A_plus_B <- A + B
> A_plus_B
[,1] [,2]
[1,] 7 5
[2,] 2 2
>
> # b) A - B
> A_minus_B <- A - B
> A_minus_B
[,1] [,2]
[1,] -3 -3
[2,] -2 4
>
> # ---------------------------------------
> # Question 2: Diagonal matrix with diag()
>
> D <- diag(c(4, 1, 2, 3))
> D
[,1] [,2] [,3] [,4]
[1,] 4 0 0 0
[2,] 0 1 0 0
[3,] 0 0 2 0
[4,] 0 0 0 3
>
> # ---------------------------------------
> # Question 3: Build the required matrix
>
> M <- diag(3, 5)
>
> M[1, ] <- c(3, 1, 1, 1, 1)
>
> M[-1, 1] <- 2
>
> M
[,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
Comments
Post a Comment