Matrix Algebra

There is a comprehensive set of functions for handling matrices in R. We begin with a matrix called a that has three rows and two columns. Data are typically entered into matrices columnwise, so the first three numbers (1, 0, 4) go in column 1 and the second three numbers (2, −1, 1) go in column 2:

a<-matrix(c(1,0,4,2,-1,1),nrow=3)
a

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

Our second matrix, called b, has the same number of columns as A has rows (i.e. three in this case). Entered columnwise, the first two numbers (1, −1) go in column 1, the second two numbers (2, 1) go in column 2, and the last two numbers (1, 0) go in column 3:

b<-matrix(c(1,-1,2,1,1,0),nrow=2)
b

       [,1]   [,2]   [,3]
[1,]      1      2      1
[2,]     -1      1      0

Matrix multiplication

To multiply one matrix by another matrix you take the rows of the first matrix and the columns of the second matrix. Put the first row of a side by side with the first column of b:

a[1,]

[1] 1 2

b[,1]

[1] 1 -1

and work out the point products:

a[1,]*b[,1]

[1] 1 -2

then add up the point products

sum(a[1,]*b[,1])

[1] -1

The sum of the point products is −1 and this is the first element of the product matrix. Next, put the first row of a with the second column of b:

a[1,]

[1] 1 2

b[,2]

[1] 2 1

a[1,]*b[,2]

[1]  2   2
sum(a[1,]*b[,2])

[1] 4

so the point products are 2, 2 and the sum of the point products is 2 + 2 = 4. So 4 goes in row 1 and column 2 of the answer. Then take the last column of b and match it against the first row of a:

a[1,]*b[,3] ...

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.