๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

R Solving Systems

solve finds the values that make a set of equations true. The same call also builds the inverse of a matrix.

The determinant of a matrix

The matrix a holds the coefficients of two equations. det reports a single number for the whole matrix.

a <- matrix(c(2, 1, 1, 1), nrow = 2)
print(a)
print(det(a))

Solve two equations

The vector b holds the total of each equation. solve works out the value of each unknown, in order.

a <- matrix(c(2, 1, 1, 1), nrow = 2)
b <- c(5, 3)
print(solve(a, b))

The inverse of a matrix

solve with no second value returns the inverse of the matrix. Every value in this inverse is a whole number.

a <- matrix(c(2, 1, 1, 1), nrow = 2)
print(solve(a))

Check the inverse

The product of a and its inverse gives the identity matrix. The ones sit on the diagonal and the other cells hold zeroes.

a <- matrix(c(2, 1, 1, 1), nrow = 2)
print(a %*% solve(a))

Example

a <- matrix(c(4, 1, 2, 1), nrow = 2)
print(det(a))
print(solve(a, c(10, 4)))
print(solve(a))

Key points

  • A system pairs each unknown with one equation.
  • solve takes the coefficient matrix as its first value.
  • A vector given as the second value holds the total each equation adds up to.
  • solve with one matrix and no vector gives the inverse of the matrix.
  • det gives the determinant of a square matrix.
  • Multiplying a matrix by its inverse gives the identity matrix.
  • The identity matrix has ones down its diagonal and zeroes in the other cells.

In this example the determinant of the matrix is 2. The system solves to 1 for the first unknown and 3 for the second. The inverse holds halves because the determinant is 2.

Note

A square matrix has the same number of rows and columns.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does print(solve(a)) show when a is a matrix?