Learn R Programming  /  Data Structures  /  Matrix

Matrix

A matrix is a two-dimensional grid of values, all of the same type. It is the natural structure for linear algebra and numeric grids in R.

Creating a Matrix

Use matrix(), giving it a vector of values plus the number of rows or columns. By default R fills the matrix column by column.

R Code
m <- matrix(1:6, nrow = 2, ncol = 3)
m
Output
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
R Code
# fill by row instead of by column
m2 <- matrix(1:6, nrow = 2, byrow = TRUE)
m2
Output
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6

Indexing a Matrix

Use m[row, column]. Leaving either side blank selects the whole row or column.

R Code
m[1, 2]     # row 1, column 2
m[1, ]      # entire first row
m[, 2]      # entire second column
m[, 2:3]   # columns 2 and 3
Output
[1] 3
[1] 1 3 5
[1] 3 4
     [,1] [,2]
[1,]    3    5
[2,]    4    6

Naming Rows and Columns

R Code
rownames(m) <- c("r1", "r2")
colnames(m) <- c("c1", "c2", "c3")
m
Output
   c1 c2 c3
r1  1  3  5
r2  2  4  6

Matrix Arithmetic

Basic operators (+ - * /) work element-by-element, just like vectors. True matrix multiplication uses a special operator, %*%.

R Code
a <- matrix(1:4, nrow = 2)
b <- matrix(5:8, nrow = 2)

a + b        # element-wise addition
a * b        # element-wise multiplication (NOT matrix multiplication)
a %*% b      # true matrix multiplication
t(a)          # transpose
Output
     [,1] [,2]
[1,]    6   10
[2,]    8   12
     [,1] [,2]
[1,]    5   21
[2,]   12   32
     [,1] [,2]
[1,]   26   38
[2,]   38   56
     [,1] [,2]
[1,]    1    2
[2,]    3    4

Advanced: Solving a Linear System

🚀 Advanced Example
matrix() and solve() together let R solve systems of linear equations directly — a common task in statistics for regression coefficients.
R Code
# solve: 2x + y = 5, x + 3y = 10
A <- matrix(c(2,1,1,3), nrow = 2)
b <- c(5, 10)

solve(A, b)   # returns values of x and y
Output
[1] 1 3

Key Points

  • A matrix is a 2-D grid where every value shares one type.
  • Index with m[row, col]; leave a side blank to select a whole row/column.
  • * multiplies element-by-element; %*% performs real matrix multiplication.
  • t() transposes, and solve() inverts a matrix or solves linear systems.