0Pricing
R Academy · Lesson

Matrix Multiplication and Determinants

Use %*% for matrix multiplication and det() for determinant calculation.

Creating Matrices in R

Matrices are 2D arrays filled column-by-column by default. Use matrix(data, nrow, ncol). You can name rows and columns with rownames() and colnames().

# Create a 3x3 matrix (filled column-wise)
A <- matrix(c(1, 2, 3,
              4, 5, 6,
              7, 8, 9), nrow = 3, ncol = 3, byrow = TRUE)
print(A)
#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]    4    5    6
# [3,]    7    8    9

dim(A)   # 3 3
nrow(A)  # 3
ncol(A)  # 3

Matrix Multiplication: %*%

The %*% operator performs true matrix multiplication (dot product of rows and columns). The * operator is element-wise — a common mistake! Dimensions must be compatible: (m×n) %*% (n×p) = (m×p).

A <- matrix(c(1, 2, 3, 4), nrow = 2)
B <- matrix(c(5, 6, 7, 8), nrow = 2)

# Element-wise multiplication (NOT matrix mult)
A * B
#      [,1] [,2]
# [1,]    5   21
# [2,]   12   32

# True matrix multiplication
A %*% B
#      [,1] [,2]
# [1,]   19   43
# [2,]   22   50

# Verify: entry [1,1] = 1*5 + 2*6 = 17... wait:
# A[1,] = c(1,3), B[,1] = c(5,6): 1*5 + 3*6 = 23

All lessons in this course

  1. Matrix Multiplication and Determinants
  2. Solving Linear Systems with solve()
  3. Eigenvalues and Eigenvectors
  4. SVD, QR, and Cholesky Decompositions
← Back to R Academy