Does there anyone know how to use R to calculate a system of linear equations with two unknowns? I have these two equations and am trying to solve for x
and y
calculate them with different values of z
.
x y=1
4.5x 9y = z
Here are the z values:
z = c(4.1, 5.5, 9.9, 7.3, 5.2, 3,5, 5,4, 4.2)
Many thanks for your help!
CodePudding user response:
Assuming you mean a series of paired equations...
z <- c(4.1, 5.5, 9.9, 7.3, 5.2, 3, 5, 5, 4, 4.2)
# equation system
# x y=1
# 4.5x 9y = z
# function to solve for each case:
solve_4z <- function(x){
left_matrix <- matrix(c(1, 4.5, 1, 9), nrow=2)
right_matrix <- matrix(c(1, x), nrow=2)
solve(left_matrix, right_matrix)
}
# data frame to capture results:
df_xy <- data.frame(z = z,
x = rep(NA_real_, length(z)),
y = rep(NA_real_, length(z)))
#loop: iterate through z to solve for x and y
for(i in seq_along(z)){
df_xy[i, 2:3] <- solve_4z(z[i])
}
# solutions:
df_xy
#> z x y
#> 1 4.1 1.0888889 -0.08888889
#> 2 5.5 0.7777778 0.22222222
#> 3 9.9 -0.2000000 1.20000000
#> 4 7.3 0.3777778 0.62222222
#> 5 5.2 0.8444444 0.15555556
#> 6 3.0 1.3333333 -0.33333333
#> 7 5.0 0.8888889 0.11111111
#> 8 5.0 0.8888889 0.11111111
#> 9 4.0 1.1111111 -0.11111111
#> 10 4.2 1.0666667 -0.06666667
Created on 2022-10-07 with reprex v2.0.2
CodePudding user response:
We can construct a system equation like Ax=b
, where
A <- t(matrix(c(1, 1, 4.5, 9), 2, 2))
b <- rbind(1, z)
x <- solve(A, b)
where the solution x
is
> x
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1.08888889 0.7777778 -0.2 0.3777778 0.8444444 1.3333333 0.8888889
[2,] -0.08888889 0.2222222 1.2 0.6222222 0.1555556 -0.3333333 0.1111111
[,8] [,9] [,10]
[1,] 0.8888889 1.1111111 1.06666667
[2,] 0.1111111 -0.1111111 -0.06666667