0Pricing
R Academy · Lesson

Solving Linear Systems with solve()

Find solutions to Ax = b systems and compute matrix inverses.

Linear Systems: Ax = b

A system of linear equations can be written as Ax = b, where A is a matrix of coefficients, x is the unknown vector, and b is the right-hand side. Solving for x analytically means computing x = A⁻¹b.

# System of equations:
# 2x + y = 5
# x + 3y = 7

# Matrix form: A %*% x = b
A <- matrix(c(2, 1,
              1, 3), nrow = 2, byrow = TRUE)
b <- c(5, 7)

# What are A and b?
print(A)
print(b)
cat('We want to find x such that A %*% x = b')

solve(A, b): The Direct Solution

solve(A, b) solves Ax = b for x. It uses LU decomposition internally, which is more numerically stable and efficient than explicitly computing A⁻¹ and then multiplying by b.

A <- matrix(c(2, 1,
              1, 3), nrow = 2, byrow = TRUE)
b <- c(5, 7)

# Solve Ax = b
x <- solve(A, b)
print(x)  # x[1] = ?, x[2] = ?

# Verify: A %*% x should equal b
residual <- A %*% x - b
print(residual)  # Should be near zero

# Manual check:
# 2*(8/5) + (9/5) = 16/5 + 9/5 = 25/5 = 5 ✓
# 1*(8/5) + 3*(9/5) = 8/5 + 27/5 = 35/5 = 7 ✓

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