Module # 6 Doing math in R part 2
Doing Math with a Matrix in RStudio Part 2
1) This week we are going to be handling more matrices in RStudio. Adding them, subtracting them and building them. I have done this a few times before so this should again, go pretty smoothly. We have three parts to tackle for this assignment so with out further ado lets jump right in.
2) I was given the following instructions for this first part: Consider A=matrix(c(2,0,1,3), ncol=2) and B=matrix(c(5,2,4,-1), ncol=2). Find A + B, and find A - B. We can easily do this with some simple code in RStudio.
> #LIS 4370 Moudle 6 assingment
> A <- matrix(c(2,0,1,3), ncol=2)
> B <- matrix(c(5,2,4,-1), ncol=2)
> #Doing the Addition
> A+B
[,1] [,2]
[1,] 7 5
[2,] 2 2
> #Doing the Subtraction
> A-B
[,1] [,2]
[1,] -3 -3
[2,] -2 4
| |
|
3) As you can see in the above code, we created both A and B matrices and then added and subtracted them, giving us two matrices.
4) For our second part we are going to use the diag() function to build a matrix of size 4 with the following values in the diagonal 4,1,2,3. Using some basic code we can have RStudio achieve this for us.
> #Building a matrix with diag()
> D_Matrix <- diag(c(4,1,2,3))
> D_Matrix
[,1] [,2] [,3] [,4]
[1,] 4 0 0 0
[2,] 0 1 0 0
[3,] 0 0 2 0
[4,] 0 0 0 3
| |
|
5) The code above does what was asked, a matrix with a size of four and the numbers 4,1,2,3 in the diagonal. Is it simple, plain and boring? Yes, but it gets the job done.
6) For our last part, we are going to make 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
7) To do this in RStudio we are going to use the diag function a lot. We could do something very boring like we did above and just manually input all the numbers into the matrix, but I want to have a little bit of fun and try to create that matrix by combining two different matrices like we did in the first part.
> #Creating two martices to then add together to get the desired result
> E_Matrix <-diag(3,5,5)
> F_Matrix <- matrix(0, nrow=5, ncol=5)
> F_Matrix[1, 2:5] <-1
> F_Matrix[2:5, 1] <- 2
> #Add both of them together
> G_Matrix <- E_Matrix + F_Matrix
> G_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
| |
|
8) What I did in the code above is basically make one matrix called E_Matrix and gave it the diagonal of what I wanted in the matrix which was all 3s for 5 columns and 5 rows. I then created another matrix that did not have any diagonals and gave it the first row and first column minus the first input, because I wanted a 3 there. Then I just added them together. Ta da. That's all for this week.
Comments
Post a Comment