简体   繁体   English

两个未知数的线性方程组

[英]system of linear equations in two unknowns

Does there anyone know how to use R to calculate a system of linear equations with two unknowns?有谁知道如何使用 R 来计算具有两个未知数的线性方程组? I have these two equations and am trying to solve for x and y calculate them with different values of z .我有这两个方程,并试图用不同的z值求解xy来计算它们。

x+y=1
4.5x+9y = z

Here are the z values:以下是 z 值:

z = c(4.1, 5.5, 9.9, 7.3, 5.2, 3,5, 5,4, 4.2)

Many thanks for your help!非常感谢您的帮助!

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创建于 2022-10-07,使用reprex v2.0.2

We can construct a system equation like Ax=b , where我们可以构造一个像Ax=b这样的系统方程,其中

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

> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM