在R中循环时,需要更有效的代码

问题描述

我写了一个R代码来共同求解以下方程。这些是需要数值过程的封闭形式的解决方案。

enter image description here

我进一步将(B)的分子和分母除以N得到算术平均值。

这是我的代码

y=cbind(Sta,Zta,Ste,Zte)           # combine the variables
St=as.matrix(y[,c(1,3)])
Stm=c(mean(St[,1]),mean(St[,2]));   # Arithmetic means of St's
Zt=as.matrix(y[,c(2,4)])
Ztm=c(mean(Zt[,mean(Zt[,2]));    # Arithmetic means of Zt's

theta=c(-20,-20);             # starting values for thetas
tol=c(10^-4,10^-4);
err=c(0,0);                  
epscon=-0.1                

while (abs(err) > tol | phicon<0) {

### A 
eps = ((mean(y[,2]^2))+mean(y[,4]^2))/(-mean(y[,1]*y[,2])+theta[1]*mean(y[,2])-mean(y[,3]*y[,4])+theta[2]*mean(y[,4]))  
### B 
thetan = Stm + (1/eps)*Ztm              
 
err=thetan-theta
theta=thetan
epscon=1-eps

print(c(ebs,theta))

}

因为不满足while循环的第二个条件,所以迭代不会停止,解决方案是正的ε。我想得到负的ε。我想这需要Thetas的网格搜索或一系列起始值。

任何人都可以帮助以不同的方式更有效地编码此过程吗?或者,如果其中有缺陷,请帮助纠正我的代码。 谢谢

解决方法

如果我是对的,使用线性关系,您的方程式为

ΘA = a + b / ε
ΘB = c + d / ε
1/ε = e ΘA + f ΘB + g

这是一个简单的3x3线性系统。