如何求解线性方程组? [英] How to solve a set of Linear equations?

查看:113
本文介绍了如何求解线性方程组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要求解线性方程组:

I need to solve a system of linear equations:

aQ + bP = c
dQ + eP = f

位置:

a ~ N(100;10)
b ~ N(-1;0.1)
c ~ N(10;1)
d ~ N(10;0.1)
e ~ N(100;10)
f ~ N(10;0.1)

到目前为止,我已经写过:

So far I have written:

a <- rnorm(100, mean=100, sd=10)
b <- rnorm(100, mean=-1, sd=0.1)
c <- rnorm(100, mean=10, sd=1)
d <- rnorm(100, mean=10, sd=0.1)
e <- rnorm(100, mean=100, sd=10)
f <- rnorm(100, mean=10, sd=0.1)

P <- vector()
Q <- vector()

for (i in 1:100) {
    coefs <- matrix(c(a[i],d[i],b[i],e[i]),2,2)
    ys <- array(c(c,f),2)
    solve(coefs[i], ys[i])
}

问题是for循环只为我提供了P和Q的一种解决方案,我希望for循环计算100个值集来进行a,b,c,d,e和f并存储向量Q和P上的数据.

The problem is that the for loop is only giving me one solution for P and Q and I would like that the for loop to calculate the 100 set of values do a, b, c, d, e and f and store the data on the vectors Q and P.

推荐答案

您可以尝试使用apply()

# data  
df = data.frame(a,b,c,d,e,f)

# apply function
out = t(apply(df, 1, 
      function(x){ 
      coefs = matrix( c(x['a'], x['d'], x['b'], x['e']), 2, 2); 
      ys = array(c(x['c'],x['f']),2); 
      out = solve(coefs, ys); 
      names(out) = c('P','Q');
      out}))

或者使用sapply()

out = t(sapply(seq(100), function(i){
       coefs = matrix(c(a[i], d[i], b[i] ,e[i]),2,2); ys = array(c(c[i],f[i]),2);
       out = solve(coefs, ys); names(out) = c('P','Q'); 
       out}))

如果您想使用for循环,这是您可以做的

and if you want to use for loop, here is what you could do

# declare matrix to store the output
out = matrix(ncol=2, nrow=100) 

# populate declared matrix using for loop
for(i in 1:100){  
    coefs = matrix(c(a[i],d[i],b[i],e[i]),2,2)
    ys = array(c(c[i],f[i]),2)
    out[i,] = as.vector(solve(coefs, ys))
    colnames(out) = c('P','Q')
    out}

这篇关于如何求解线性方程组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆