Appendix

This page accompanies the Appendix of O’Sullivan and Unwin (2010).

Add two matrices

A <- matrix(1:4, nrow=2, byrow=TRUE)
B <- matrix(5:8, nrow=2, byrow=TRUE)
A + B
##      [,1] [,2]
## [1,]    6    8
## [2,]   10   12

Matrix multiplication

A <- matrix(c(1,-4,-2,5,3,-6), nrow=2)
B <- matrix(c(6,4,2,-5,-3,-1), nrow=3)
A %*% B
##      [,1] [,2]
## [1,]    4   -2
## [2,]  -16   11
B %*% A
##      [,1] [,2] [,3]
## [1,]   26  -37   48
## [2,]   16  -23   30
## [3,]    6   -9   12

Matrix transposition

A <- matrix(1:6, nrow=2, byrow=TRUE)
A
##      [,1] [,2] [,3]
## [1,]    1    2    3
## [2,]    4    5    6
t(A)
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    5
## [3,]    3    6

Identity matrix

I <- matrix(0, ncol=2, nrow=2)
diag(I) <- 1
I
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1
I <- matrix(0, ncol=5, nrow=5)
diag(I) <- 1
I
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    0    0    0    0
## [2,]    0    1    0    0    0
## [3,]    0    0    1    0    0
## [4,]    0    0    0    1    0
## [5,]    0    0    0    0    1

Finding the inverse matrix

A <- matrix(1:4, nrow=2, byrow=TRUE)
Inv <- solve(A)
Inv
##      [,1] [,2]
## [1,] -2.0  1.0
## [2,]  1.5 -0.5
AA <- A %*% Inv
AA
##      [,1]         [,2]
## [1,]    1 1.110223e-16
## [2,]    0 1.000000e+00
round(AA, 10)
##      [,1] [,2]
## [1,]    1    0
## [2,]    0    1

inv(AB) == inv(A) * inv(B)

A <- matrix(1:4, nrow=2, byrow=TRUE)
B <- matrix(4:1, nrow=2, byrow=TRUE)
AB <- A %*% B
solve(AB)
##       [,1]  [,2]
## [1,]  3.25 -1.25
## [2,] -5.00  2.00
# the same as
solve(B) %*% solve(A)
##       [,1]  [,2]
## [1,]  3.25 -1.25
## [2,] -5.00  2.00

Simulataneous equations

A <- matrix(c(3,2,4,-4), nrow=2)
b <- matrix(c(11, -6))
solve(A) %*% b
##      [,1]
## [1,]    1
## [2,]    2

Rotation

A <- matrix(c(.6,-.8,.8,.6), nrow=2)
s <- matrix(c(3, 4))
As <- A %*% s
round(As, 10)
##      [,1]
## [1,]    5
## [2,]    0
S <- matrix(c(1,1,3,-2,0,5,-1,4,-2.5,-4), nrow=2)
AS <- A %*% S
AS
##      [,1] [,2] [,3] [,4] [,5]
## [1,]  1.4  0.2    4  2.6 -4.7
## [2,] -0.2 -3.6    3  3.2 -0.4

The angle of rotation matrix A is

angle <- acos(A[1])
angle
## [1] 0.9272952
# in degrees
180*angle/ pi
## [1] 53.1301

See this page for more on rotation matrices.

Eigenvector and values

M <- matrix(c(3,2,4,-4), nrow=2)
eigen(M)
## eigen() decomposition
## $values
## [1] -5  4
##
## $vectors
##            [,1]      [,2]
## [1,] -0.4472136 0.9701425
## [2,]  0.8944272 0.2425356
M <- matrix(c(1,3,3,2), nrow=2)
eigen(M)
## eigen() decomposition
## $values
## [1]  4.541381 -1.541381
##
## $vectors
##           [,1]       [,2]
## [1,] 0.6463749 -0.7630200
## [2,] 0.7630200  0.6463749