Module 6 – Matrix math and simulations in R Part 2

The assignment this week involved performing math with matrices, building a matrix with diag(), and generating a specific matrix.

The code for my solution is on github here:

https://github.com/jered0/lis4930-rpackage/blob/master/module6/matrices2.r

The first part was straightforward – A + B…

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

…and A - B:

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

Next we were to generate a 4×4 matrix with a diagonal of (4, 1, 2, 3). After poking around with the diag() command, that turned out to be a one-line command:

diag(c(4, 1, 2, 3))

With the result:

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

Finally, we were to create a specific 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

I started out by using integer(25) to create an empty matrix, but had overlooked the hint in the question suggesting that I use diag() to create the matrix instead. That made for more compact code, so I made the matrix using a combination of diag() and rep(). Then I wrote the last 4 entries in the first row with all 1s, and the last 4 entries in column 1 with all 2s, again using rep(). The code looked like this:

C <- diag(rep.int(3, 5))
C[1,2:5] <- rep.int(1, 4)
C[2:5,1] <- rep.int(2, 4)
This entry was posted in R Programming. Bookmark the permalink.

Comments are closed.