matrix()

matrix(data, nrow, ncol, byrow, dimnames)
Returns: matrix · Updated March 13, 2026 · Data Types
matrix data-type linear-algebra base

Matrices are two-dimensional data structures in R that hold elements of the same atomic type. They are fundamental to statistical computing and linear algebra.

Syntax

matrix(data, nrow, ncol, byrow, dimnames)

Parameters

ParameterTypeDefaultDescription
dataanyAn atomic vector (or scalar) to fill the matrix
nrowintegerNumber of rows
ncolintegerNumber of columns
byrowlogicalFALSEFill matrix by rows if TRUE, by columns if FALSE
dimnameslistNULLOptional row and column names

Examples

Basic matrix creation

# Create a 3x2 matrix filled column-wise (default)
mat <- matrix(1:6, nrow = 3, ncol = 2)
mat
#      [,1] [,2]
# [1,]    1    4
# [2,]    2    5
# [3,]    3    6

# Fill by rows instead
mat_by_row <- matrix(1:6, nrow = 3, ncol = 2, byrow = TRUE)
mat_by_row
#      [,1] [,2]
# [1,]    1    2
# [2,]    3    4
# [3,]    5    6

Named rows and columns

# Add row and column names
mat <- matrix(1:6, nrow = 3, ncol = 2,
              dimnames = list(c("r1", "r2", "r3"),
                              c("c1", "c2")))
mat
#    c1 c2
# r1  1  4
# r2  2  5
# r3  3  6

Matrix operations

# Matrix multiplication
A <- matrix(1:4, nrow = 2)
B <- matrix(5:8, nrow = 2)
A %*% B
#      [,1] [,2]
# [1,]   23   34
# [2,]   34   50

# Transpose
t(A)
#      [,1] [,2]
# [1,]    1    3
# [2,]    2    4

# Row and column sums
rowSums(A)
# [1] 3 7
colSums(A)
# [1] 4 6

Common Patterns

Matrix indexing

mat <- matrix(1:9, nrow = 3)

# Access element
mat[2, 3]
# [1] 8

# Access row
mat[1, ]
# [1] 1 4 7

# Access column
mat[, 2]
# [1] 4 5 6

Binding vectors

# Combine vectors as rows
rbind(1:3, 4:6)
#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    4    5    6

# Combine vectors as columns
cbind(1:3, 4:6)
#      [,1] [,2]
# [1,]    1    4
# [2,]    2    5
# [3,]    3    6

Diagonal matrices

# Identity matrix
diag(3)
#      [,1] [,2] [,3]
# [1,]    1    0    0
# [2,]    0    1    0
# [3,]    0    0    1

# Custom diagonal
diag(c(1, 2, 3))
#      [,1] [,2] [,3]
# [1,]    1    0    0
# [2,]    0    2    0
# [3,]    0    0    3

See Also