# R Matrix Exercises¶

Through these exercises we will review the matrix data structure and perhaps introduce you to a few ideas for you to discover on your own! Just answer the questions below written in bold:

Ex 1: Create 2 vectors A and B, where A is (1,2,3) and B is (4,5,6). With these vectors, use the cbind() or rbind() function to create a 2 by 3 matrix from the vectors. You'll need to figure out which of these binding functions is the correct choice.

In [5]:

Out[5]:

A | 1 | 2 | 3
B | 4 | 5 | 6

Ex 2: Create a 3 by 3 matrix consisting of the numbers 1-9. Create this matrix using the shortcut 1:9 and by specifying the nrow argument in the matrix() function call. Assign this matrix to the variable mat

In [6]:

Ex 3: Confirm that mat is a matrix using is.matrix()

In [7]:

Out[7]:
TRUE

Ex 4: Create a 5 by 5 matrix consisting of the numbers 1-25 and assign it to the variable mat2. The top row should be the numbers 1-5.

In [11]:

Out[11]:

1 | 2 | 3 | 4 | 5
6 | 7 | 8 | 9 | 10
11 | 12 | 13 | 14 | 15
16 | 17 | 18 | 19 | 20
21 | 22 | 23 | 24 | 25

Ex 5: Using indexing notation, grab a sub-section of mat2 from the previous exercise that looks like this:

    [7,8]
    [12,13]

In [12]:

Out[12]:

7 | 8
12 | 13

Ex 6: Using indexing notation, grab a sub-section of mat2 from the previous exercise that looks like this:

    [19,20]
    [24,25]

In [17]:

Out[17]:

19 | 20
24 | 25

Ex 7: What is the sum of all the elements in mat2?

In [18]:

Out[18]:
325

Ex 8: Ok time for our last exercise! Find out how to use runif() to create a 4 by 5 matrix consisting of 20 random numbers (4*5=20).

In [25]:

Out[25]:

21.03996 | 41.21689 | 51.46716 | 35.24451 | 65.69687
60.812696 | 81.326606 | 81.545300 | 94.459102 | 3.403767
72.13241 | 32.48194 | 18.74600 | 35.16303 | 90.70033
1.798345 | 35.558233 | 94.300991 | 17.991320 | 11.074018

In [1]:

    #help(runif)

# Great Job!¶