0Pricing
R Academy · Lesson

Matrix Multiplication and Determinants

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

Matrix Multiplication and Determinants is a free R Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

Understanding %*% Results

Let's verify matrix multiplication manually. The (i,j) entry of C = A %*% B is the dot product of row i of A with column j of B: sum(A[i,] * B[,j]).

A <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, byrow = TRUE)
B <- matrix(c(7, 8, 9, 10, 11, 12), nrow = 3, byrow = TRUE)
# A is 2x3, B is 3x2 -> result is 2x2
C <- A %*% B
print(C)

# Verify entry C[1,1]:
# row 1 of A: c(1,2,3), col 1 of B: c(7,9,11)
manual_11 <- sum(A[1, ] * B[, 1])
manual_11  # 1*7 + 2*9 + 3*11 = 58
C[1, 1]   # should match

The Determinant: det()

The determinant is a scalar value encoding a matrix's scaling factor. det(A) computes it. If det(A) == 0, the matrix is singular (non-invertible). For a 2×2 matrix, det = ad - bc.

# 2x2 matrix: det = a*d - b*c
A <- matrix(c(3, 2, 1, 4), nrow = 2)
det(A)  # 3*4 - 2*1 = 10

# Singular matrix: det = 0
S <- matrix(c(1, 2, 2, 4), nrow = 2)
det(S)  # 0 -> not invertible

# Larger matrix
B <- matrix(c(2, -1, 0,
             -1,  2, -1,
              0, -1,  2), nrow = 3, byrow = TRUE)
det(B)  # 4

Trace: sum(diag())

The trace of a matrix is the sum of its diagonal elements. R has no built-in trace() for matrices (it's a different function), so use sum(diag(A)). The trace equals the sum of eigenvalues.

A <- matrix(c(4, 2, 1,
              3, 5, 0,
              2, 1, 6), nrow = 3, byrow = TRUE)
# Extract diagonal elements
diag(A)  # c(4, 5, 6)

# Trace = sum of diagonal
trace_A <- sum(diag(A))
trace_A  # 15

# Trace = sum of eigenvalues (verify)
eigs <- eigen(A)$values
sum(Re(eigs))  # should also be approximately 15

# trace() in base R is NOT the matrix trace:
# trace(A) # this does something else

crossprod() and tcrossprod()

crossprod(A, B) computes t(A) %*% B efficiently — the cross-product. tcrossprod(A, B) computes A %*% t(B). These are faster than the explicit transpose because they avoid creating the transposed matrix.

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

# t(A) %*% B  (the slow way)
result1 <- t(A) %*% B

# crossprod(A, B) = t(A) %*% B (faster)
result2 <- crossprod(A, B)
all.equal(result1, result2)  # TRUE

# crossprod(A) = t(A) %*% A
ATA <- crossprod(A)
print(ATA)

# tcrossprod(A, B) = A %*% t(B)
result3 <- tcrossprod(A, B)
all.equal(A %*% t(B), result3)  # TRUE

Identity Matrix with diag()

diag(n) creates an n×n identity matrix. diag(v) where v is a vector creates a diagonal matrix with v on the diagonal. diag(A) where A is a matrix extracts the diagonal.

# 3x3 identity matrix
I3 <- diag(3)
print(I3)
#      [,1] [,2] [,3]
# [1,]    1    0    0
# [2,]    0    1    0
# [3,]    0    0    1

# A * I = A (identity property)
A <- matrix(c(2, 3, 4, 5), nrow = 2)
all.equal(A %*% diag(2), A)  # TRUE

# Create diagonal matrix from vector
D <- diag(c(2, 5, 10))
print(D)
det(D)  # Product of diagonal: 100

Matrix Power and Repeated Multiplication

R has no built-in matrix power operator, but you can write one using %*% in a loop or use the expm package. The matrix square A² = A %*% A is a common operation.

# Matrix square
A <- matrix(c(1, 1, 1, 0), nrow = 2)
A_sq <- A %*% A
print(A_sq)
# Fibonacci connection: A^n gives Fib numbers!

# Simple matrix power function
mat_pow <- function(M, n) {
  result <- diag(nrow(M))  # start with identity
  for (i in seq_len(n)) result <- result %*% M
  result
}

mat_pow(A, 5)  # A to the 5th power
# [1,]  8  5
# [2,]  5  3

Outer Product with %o%

The outer product x %o% y creates a matrix where entry (i,j) = x[i] * y[j]. Equivalent to outer(x, y). Useful for creating interaction matrices and certain mathematical constructions.

x <- c(1, 2, 3)
y <- c(10, 20)

# Outer product: 3x2 matrix
P <- x %o% y
print(P)
#      [,1] [,2]
# [1,]   10   20
# [2,]   20   40
# [3,]   30   60

# Same as outer(x, y)
identical(P, outer(x, y))  # TRUE

# Outer with custom function
outer(1:3, 1:3, FUN = '+')
#      [,1] [,2] [,3]
# [1,]    2    3    4
# [2,]    3    4    5
# [3,]    4    5    6

Determinant Properties

Key properties: det(A %*% B) = det(A) * det(B); det(t(A)) = det(A); det(k*A) = k^n * det(A) for n×n matrix; row operations change det in predictable ways.

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

# det(A %*% B) = det(A) * det(B)
det(A %*% B)
det(A) * det(B)

# det(t(A)) = det(A)
det(t(A)); det(A)

# det(2A) = 2^n * det(A) for n=2
det(2 * A); 2^2 * det(A)

# det of upper triangular = product of diagonal
U <- matrix(c(3, 0, 0, 4, 2, 0, 1, 5, 7), nrow = 3, byrow = TRUE)
det(U); prod(diag(U))  # both = 42

Practical: Normal Equations

In linear regression, the OLS estimator solves t(X) %*% X %*% beta = t(X) %*% y. This uses matrix multiplication and the condition det(t(X)%*%X) != 0 to ensure a unique solution.

# Generate simple regression data
set.seed(42)
n <- 20
x <- runif(n, 0, 10)
y <- 2 + 3 * x + rnorm(n)

# Design matrix with intercept column
X <- cbind(1, x)

# Check det of X'X (should be nonzero)
XtX <- crossprod(X)  # t(X) %*% X
det(XtX)  # large positive value

# Solve normal equations: beta = solve(X'X) %*% X'y
Xty <- crossprod(X, y)  # t(X) %*% y
beta <- solve(XtX) %*% Xty
beta  # Should be close to c(2, 3)

# Compare with lm()
coef(lm(y ~ x))  # same result

Quick Check

Test your understanding of matrix operations in R.

Recap: Matrix Operations

Key takeaways: Use %*% for matrix multiplication (not *). det(A) gives the determinant — zero means singular. sum(diag(A)) is the trace. crossprod(A,B) efficiently computes t(A)%*%B. diag(n) creates the identity; diag(v) makes a diagonal matrix. These operations underlie regression, PCA, and many numerical methods.

A <- matrix(c(2, 1, 1, 3), nrow = 2)
B <- matrix(c(1, 0, 0, 1), nrow = 2)  # Identity

# Core matrix operations summary:
A %*% B             # matrix multiply -> A
det(A)              # 2*3 - 1*1 = 5
sum(diag(A))        # trace = 2+3 = 5
crossprod(A)        # t(A) %*% A
tcrossprod(A)       # A %*% t(A)
diag(3)             # 3x3 identity
diag(c(1,2,3))      # diagonal matrix
A %o% c(1, 2)       # outer product

Frequently asked questions

Is the “Matrix Multiplication and Determinants” lesson free?

Yes — the full text of “Matrix Multiplication and Determinants” is free to read here on the web, and the R Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the R Academy course, upgrade to CoddyKit PRO.

What will I learn in “Matrix Multiplication and Determinants”?

Use %*% for matrix multiplication and det() for determinant calculation. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Matrix Multiplication and Determinants” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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