Matrices and arrays

Author

Søren O’Neill & Steen Harsted

Published

February 8, 2024


1 Matrices

Like data frames, matrices are 2-dimensional rectangular data structures where each column must have the same number of rows, and vice versa.

Additionally, a matrix can only contain one data type across all cells.

This means, e.g. that you can do matrix arithmatic with matrices, which you can not with data frames:

m1 <- matrix(1:9, ncol=3, byrow=TRUE)
m2 <- matrix(1:9, ncol=3, byrow=FALSE)
m1
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
m2
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
m1+m2
     [,1] [,2] [,3]
[1,]    2    6   10
[2,]    6   10   14
[3,]   10   14   18

2 Arrays

Matrices are special 2-dimensional cases of Arrays, which can be multi dimensional:

a1 <- 1:24
dim(a1) <- c(3,2,4) # 3 rows, 2 columns, 4 layers
a1
, , 1

     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

, , 2

     [,1] [,2]
[1,]    7   10
[2,]    8   11
[3,]    9   12

, , 3

     [,1] [,2]
[1,]   13   16
[2,]   14   17
[3,]   15   18

, , 4

     [,1] [,2]
[1,]   19   22
[2,]   20   23
[3,]   21   24

3 Matriser

Ligesom datasæt (data frames/tibbles) er matriser 2-dimensionelle rektangulære datastrukturer, hvor hver kolonne skal have det samme antal rækker og omvendt.

Derudover kan en matrise kun indeholde én datatype på tværs af alle celler.

Dette betyder fx, at du kan udføre matriserregning med matriser, hvilket du ikke kan med datasæt:

m1 <- matrix(1:9, ncol=3, byrow=TRUE)
m2 <- matrix(1:9, ncol=3, byrow=FALSE)
m1
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9
m2
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
m1+m2
     [,1] [,2] [,3]
[1,]    2    6   10
[2,]    6   10   14
[3,]   10   14   18

4 Arrays

Matriser er specielle 2-dimensionelle tilfælde af Arrays, som kan være multidimensionelle:

a1 <- 1:24
dim(a1) <- c(3,2,4) # 3 rækker, 2 kolonner, 4 lag
a1
, , 1

     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

, , 2

     [,1] [,2]
[1,]    7   10
[2,]    8   11
[3,]    9   12

, , 3

     [,1] [,2]
[1,]   13   16
[2,]   14   17
[3,]   15   18

, , 4

     [,1] [,2]
[1,]   19   22
[2,]   20   23
[3,]   21   24