Doing mathematics with R: Linear algebra in R
Basic properties and creation of matrices
Matrices are in R two-dimensional arrays. You can think of a structure of row vectors of equal length which are placed under each other. You can display as well as specify the shape of a matrix via the dim
function
> A <- 1:6 # 1-dimensional array with 6 element
> dim(A) <- c(2,3) # convert to 2-dimensional array with 2 rows and 3 columns
> A; # display as 2x3 matrix
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
> B <- matrix( 1:6, ncol=2) # alternative matrix definition
> B
[,1] [,2]
[1,] 1 4
[2,] 2 5
[3,] 3 6
> dim(B) # B is a 3x2 matrix filled columnwise
[1] 3 2
> C <- matrix( 1:6, ncol=2, byrow=TRUE); # C is a 3x2 matrix filled row by row
> C
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
\(\phantom{x}\)
We illustrate other commonly used methods for creating arrays with examples.
Construction of a matrix by repetition loops
> A <- matrix(0, nrow=3, ncol=4); A # 3x4 zero matrix
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 0 0 0 0
[3,] 0 0 0 0
> for (i in 1:3) {
for (j in 1:4) {
A[i,j] <- i^j
}
} # assigning individual matrix elements
> A
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 2 4 8 16
[3,] 3 9 27 81
Construction of a matrix via an indexing function and the outer function
> A <- outer(1:3, 1:4, FUN=function(i,j){i^j}); A
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 2 4 8 16
[3,] 3 9 27 81
Construction of a special matrix There are also special ways to create matrices and vectors with ones and zeros and to create diagonal matrices and identity matrices (via diag
):
> Z <- matrix(0, 2, 4); Z # zero matrix with 2 rows and 4 columns
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 0 0 0 0
> I <- diag(3); I # 3x3 identity matrix
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
> J <- matrix(1, 3, 3); J # 3x3 matrix with all elements equal to 1
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 1 1 1
[3,] 1 1 1
> D <- diag(1:3); D # diagonal matrix
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 2 0
[3,] 0 0 3
Construction of a matrix by stacking Arrays can also be stacked horizontally (cbind
) and vertically (rbind
):
> A
[,1] [,2] [,3] [,4]
[1,] 1 1 1 1
[2,] 2 4 8 16
[3,] 3 9 27 81
> I
[,1] [,2] [,3]
[1,] 1 0 0
[2,] 0 1 0
[3,] 0 0 1
> AI <- cbind(A,I); AI
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 1 1 1 1 0 0
[2,] 2 4 8 16 0 1 0
[3,] 3 9 27 81 0 0 1
> ZAZ <- rbind(Z,A,Z); ZAZ
[,1] [,2] [,3] [,4]
[1,] 0 0 0 0
[2,] 0 0 0 0
[3,] 1 1 1 1
[4,] 2 4 8 16
[5,] 3 9 27 81
[6,] 0 0 0 0
[7,] 0 0 0 0
Construction of a random matrix You can create randomly generated matrices.
> # random 3x2 matrix with numbers between 0 and 1
> matrix(runif(6), nrow=3)
[,1] [,2]
[1,] 0.4605161 0.03090664
[2,] 0.9818785 0.82348871
[3,] 0.4128821 0.65200366
> # random 2x2 matrix using the standard normal distribution
> matrix(rnorm(4), nrow=2)
[,1] [,2]
[1,] -0.3502606 0.8576934
[2,] -1.6379942 0.9516872
> # random 2x3 matrix with integers in [5, 8]
> matrix(sample(5:8, 6, replace=TRUE), nrow=2)
[,1] [,2] [,3]
[1,] 8 5 7
[2,] 7 6 5