Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solve a linear system of equations in R

Tags:

I don’t know how to proceed in the following case because the last equation doesn’t have all the 4 variables. So used the code below the equation, but this is wrong... Does anyone know the way to proceed?

Euqations:

3a + 4b - 5c + d = 10

2a + 2b + 2c - d = 5

a -b + 5c - 5d = 7

5a + d = 4

Code:

 X <- matrix(c(3,4,-5,1,2,2,2,-1,1,-1,5,-5,5,0,0,1), 4, 4)
 y <- matrix(c(10,5,7,4), 4, 1)
 solve(X)%*%y #equivalent to solve(X, y)
like image 570
Afonso O. Lenzi Avatar asked Nov 01 '18 01:11

Afonso O. Lenzi


1 Answers

Setting the argument byrow of matrix() to TRUE does the trick:

X <- matrix(c(3, 4,-5, 1,
              2, 2, 2,-1,
              1,-1, 5,-5,
              5, 0, 0, 1), 4, 4, byrow=TRUE)
y <- c(10, 5, 7, 4)
sol <- solve(X, y)

Check if correct:

c(X %*% sol)
[1] 10  5  7  4

By the way, solve(X, y) is computationally more efficient than solve(X) %*% y.

like image 77
Nairolf Avatar answered Nov 15 '22 05:11

Nairolf