Solving “n” equations with 3 unknowns

I'm new to R and I'm trying to solve a system of equations. I have about 380 equations where i have 3 unknowns per equation. I can use three equations and solve by using "solve()" and it works great. I used this link to make that works:

Solving simultaneous equations with R

Now, how do I optimize my result so it best fits across the rest of the 377 equations? I saw an optimization page on CRAN but I couldn't make much use of it. I'm still researching and I will post any solution that I find.

migrated from stackoverflow.comJul 1 '15 at 8:51

This question came from our site for professional and enthusiast programmers.

• can you be more clear about what you mean by "optimize my result so it best fits across the rest of the 377 equations"? I don't understand what you are trying to do. – C8H10N4O2 Jun 26 '15 at 17:17
• Sorry. Should've been more clear. I can choose any 3 equations (of the 380) and get the 3 unknowns. What I want is the value of the 3 unknowns that solves all the 380 equations as close as possible. (i realize that you cannot have them solved exactly). Don't even know if it is possible. I'm thinking maybe solve all possible combinations of 3 equations and averaging the value of the unknowns could be one way. – user1387874 Jun 26 '15 at 17:23
• Are the equations all linear? – C8H10N4O2 Jun 26 '15 at 17:43
• It sounds like a regression problem to me. Maybe applying lm() will be sufficient. – RHertel Jun 26 '15 at 17:51
• Whatever you are trying to do I doubt that solving 380-choose-3 (9.1e6) systems of equations is the right approach – C8H10N4O2 Jun 26 '15 at 18:15

If your equations are linear, as suggested by the link you provide, you need to do linear regression to solve all the equations simultaneously:

# creating some random data
set.seed(123)
N = 280
# Ax = b is the system to solve
A = matrix(sample(1:100, 3*N, replace=TRUE), ncol=3, nrow=N)
colnames(A) = c("x", "y", "z")
b = sample(1:100, N, replace=TRUE)

# first system
ind0 = sample(N, 3) # 3 random equations
solve(A[ind0,], b[ind0])

# x         y         z
# -6.054476  6.898068 -4.457295

# second system
ind1 = sample(N, 3) # another 3 random equations
solve(A[ind1,], b[ind1])

# x         y         z
# 0.5521134 0.5771540 0.5728314

# solving for all equations
sol = lm(b ~ . + 0, data=data.frame(A, b))

coef(sol)

# x         y         z
# 0.1514154 0.3657049 0.3767679