Module 6: Doing Math Part 2
In this module, we are tasked with performing math with different matrices.
In step 1, we are tasked with making the 2 following matrices and performing A+B and A-B.
A = matrix(c(2,0,1,3), ncol=2)
B = matrix(c(5,2,4,-1), ncol=2)
B = matrix(c(5,2,4,-1), ncol=2)
> A+B
[,1] [,2]
[1,] 7 5
[2,] 2 2> A-B
[,1] [,2]
[1,] -3 -3
[2,] -2 4
After Running the code we get the following outputs for A+B and A-B.
For step 2 we are tasked with building a matrix of size for with the following in a diagonal, 4,1,2,3 using the diag() function. We can use the following code to create this matrix using the diag() function.
diag(c(4,1,2,3))
> diag(c(4,1,2,3))
[,1] [,2] [,3] [,4]
[1,] 4 0 0 0
[2,] 0 1 0 0
[3,] 0 0 2 0
[4,] 0 0 0 3
After running the diag() function with the given numbers we in fact get a matrix with the numbers 4,1,2,3 in a diagonal like the instructions require.
In step 3 we are tasked with generating a matrix of 5 with a diagonal of 3,3,3,3,3. To do that first we can use the diag() function to get started with the diaognal of 3. I am going to use the diag() function and store it in a variable so later we can add the remaining numbers to the matrix. The following code is using the diag() funciton to get started building the matrix.
mt = diag(3, 5)
After running that we get the following output:
> mt
[,1] [,2] [,3] [,4] [,5]
[1,] 3 0 0 0 0
[2,] 0 3 0 0 0
[3,] 0 0 3 0 0
[4,] 0 0 0 3 0
[5,] 0 0 0 0 3
Now all we have left is to modify the first column and the first row to add the numbers 1 across row 1 and the number 2 down column 1. To do so we can modifiy the matrix that was stored in the variable mt.
We can first modify the first row using the following line of code.
mt[1,] = c(3,1,1,1,1)
> mt
[,1] [,2] [,3] [,4] [,5]
[1,] 3 1 1 1 1
[2,] 0 3 0 0 0
[3,] 0 0 3 0 0
[4,] 0 0 0 3 0
[5,] 0 0 0 0 3
Now we just have to modify the first clomun and for that we can use the following line of code to add the number 2 going down without changing the number in the [1,1].
mt[2:5,1] = 2
Now after fnishing that last modification of mt we can call it again and check to make sure we have the correct matrix built.
> mt
[,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
Finally we have the correct matrix that the assignment called for. In this module we learn the importance of the funciton diag() and how to correctly apply it when working with matrices. I also go more pratice modifying different rows and columns inside a matrix which is always great to get more hands on experience with matrices. This excersie defnitively strengthen my skills, and confidence when it comes to working with matrices.
Comments
Post a Comment