1.5 Diagonal matrices and identity matrices
A diagonal matrix is one that is square, meaning number of rows equals number of columns, and it has 0s on the off-diagonal and non-zeros on the diagonal. In R, you form a diagonal matrix with the diag()
function:
diag(1,3) #put 1 on diagonal of 3x3 matrix
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
diag(2, 3) #put 2 on diagonal of 3x3 matrix
[,1] [,2] [,3]
[1,] 2 0 0
[2,] 0 2 0
[3,] 0 0 2
diag(1:4) #put 1 to 4 on diagonal of 4x4 matrix
[,1] [,2] [,3] [,4]
[1,] 1 0 0 0
[2,] 0 2 0 0
[3,] 0 0 3 0
[4,] 0 0 0 4
The diag()
function can also be used to replace elements on the diagonal of a matrix:
= matrix(3, 3, 3)
A diag(A) = 1
A
[,1] [,2] [,3]
[1,] 1 3 3
[2,] 3 1 3
[3,] 3 3 1
= matrix(3, 3, 3)
A diag(A) = 1:3
A
[,1] [,2] [,3]
[1,] 1 3 3
[2,] 3 2 3
[3,] 3 3 3
= matrix(3, 3, 4)
A diag(A[1:3, 2:4]) = 1
A
[,1] [,2] [,3] [,4]
[1,] 3 1 3 3
[2,] 3 3 1 3
[3,] 3 3 3 1
The diag()
function is also used to get the diagonal of a matrix.
= matrix(1:9, 3, 3)
A diag(A)
[1] 1 5 9
The identity matrix is a special kind of diagonal matrix with 1s on the diagonal. It is denoted \(\mathbf{I}\). \(\mathbf{I}_3\) would mean a \(3 \times 3\) diagonal matrix. A identity matrix has the property that \(\mathbf{A}\mathbf{I}=\mathbf{A}\) and \(\mathbf{I}\mathbf{A}=\mathbf{A}\) so it is like a 1.
= matrix(1:9, 3, 3)
A = diag(3) #shortcut for 3x3 identity matrix
I %*% I A
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9