Linear Algebra in R
By admin on October 21, 2019
Linear algebra is a branch of mathematics that consists of a set of tools to solve equations like this -
7x + 2y = 13
4x - y = 1
We will use the R package “matlib” for this purpose. Install it, if you do not have it yet, and then load the library. This package gives you a number of functions for solving linear equations.
library(matlib)
The function ‘matrix’ allows you to turn a vector into matrix. This package gives you a number of functions for solving linear equations.
A = matrix(1:10, nrow=2, ncol=5, byrow=TRUE)
A = matrix(1:10, nrow=2, ncol=5, byrow=FALSE)
To solve the equation, we will create matrix with numbers, apply matlib functions ‘showEqn’ to make sure the equation is correct and then ‘Solve’.
A <- matrix(c(7,4,2,-1),2,2)
b <- c(13,1)
#
#
showEqn(A,b)
## 7*x1 + 2*x2 = 13
## 4*x1 - 1*x2 = 1
Solve(A,b)
## x1 = 1
## x2 = 3
Solve(A,b,fractions=TRUE)
## x1 = 1
## x2 = 3
Let us have a bit more practice with another equation -
3x + 7y = 3
4x - 5y = -5
A <-matrix(c(3,4,7,-5),2,2)
b <- c(3,-5)
#
#
showEqn(A,b)
## 3*x1 + 7*x2 = 3
## 4*x1 - 5*x2 = -5
Solve(A,b,fractions=TRUE)
## x1 = -20/43
## x2 = 27/43
Here is a three variable equation.
x + 7y + z = 30
2x - y - z = 5
x - y +3z = 12
A <-matrix(c(1,2,1,7,-1,-1,1,-1,3),3,3)
b <- c(30,5,12)
#
#
showEqn(A,b)
## 1*x1 + 7*x2 + 1*x3 = 30
## 2*x1 - 1*x2 - 1*x3 = 5
## 1*x1 - 1*x2 + 3*x3 = 12
Solve(A,b,fractions=TRUE)
## x1 = 151/27
## x2 = 82/27
## x3 = 85/27