如何在 r 中向量化复杂的迭代循环
How to vectorize complex iterative loop in r
我通常对 r 中的矢量化没有问题,但我在下面的示例中遇到了困难,因为 for 循环中同时存在迭代和非迭代组件。
在下面的代码中,我必须根据一组常量 (Dini)、一个值向量 (Xs) 执行计算,其中输出向量 (Ys) 的第 i 个值也是取决于 i-1 值:
Dini=128 #constant
Xs=c(6.015, 5.996, 5.989, 5.911, 5.851, 5.851, 5.858, 5.851)
Y0=125.73251 #starting Y value
Ys=c(Y0) #starting of output vector, first value is known
for (Vi in Xs[2:length(Xs)]){
ytm1=Ys[length(Ys)]
y=(955.74301-2*((Dini+ytm1-Vi)^2-ytm1^2)^0.5+2*ytm1*acos(ytm1/(Dini+ytm1-Vi)))/pi/2
Ys=c(Ys, y)
}
df=data.frame(Xs, Ys)
df
Xs Ys
1 6.015 125.7325
2 5.996 125.7273
3 5.989 125.7251
4 5.911 125.7036
5 5.851 125.6859
6 5.851 125.6849
7 5.858 125.6868
8 5.851 125.6850
对于这种情况,在 for 循环中混合了迭代和非迭代组件,我的思绪被扭曲成一个非矢量化的结。
有什么建议吗?
在这种情况下,您可能需要考虑使用 Reduce
。例如
Ys<-Reduce(function(prev, cur) {
(955.74301-2*((Dini+prev-cur)^2-prev^2)^0.5 + 2*prev*acos(prev/(Dini+prev-cur)))/pi/2
}, Xs, init=Y0, accumulate=T)[-1]
来自 ?Reduce
帮助页面:"Reduce uses a binary function to successively combine the elements of a given vector and a possibly given initial value." 这使得创建给定值取决于先前值的向量变得更加容易。
我通常对 r 中的矢量化没有问题,但我在下面的示例中遇到了困难,因为 for 循环中同时存在迭代和非迭代组件。
在下面的代码中,我必须根据一组常量 (Dini)、一个值向量 (Xs) 执行计算,其中输出向量 (Ys) 的第 i 个值也是取决于 i-1 值:
Dini=128 #constant
Xs=c(6.015, 5.996, 5.989, 5.911, 5.851, 5.851, 5.858, 5.851)
Y0=125.73251 #starting Y value
Ys=c(Y0) #starting of output vector, first value is known
for (Vi in Xs[2:length(Xs)]){
ytm1=Ys[length(Ys)]
y=(955.74301-2*((Dini+ytm1-Vi)^2-ytm1^2)^0.5+2*ytm1*acos(ytm1/(Dini+ytm1-Vi)))/pi/2
Ys=c(Ys, y)
}
df=data.frame(Xs, Ys)
df
Xs Ys
1 6.015 125.7325
2 5.996 125.7273
3 5.989 125.7251
4 5.911 125.7036
5 5.851 125.6859
6 5.851 125.6849
7 5.858 125.6868
8 5.851 125.6850
对于这种情况,在 for 循环中混合了迭代和非迭代组件,我的思绪被扭曲成一个非矢量化的结。
有什么建议吗?
在这种情况下,您可能需要考虑使用 Reduce
。例如
Ys<-Reduce(function(prev, cur) {
(955.74301-2*((Dini+prev-cur)^2-prev^2)^0.5 + 2*prev*acos(prev/(Dini+prev-cur)))/pi/2
}, Xs, init=Y0, accumulate=T)[-1]
来自 ?Reduce
帮助页面:"Reduce uses a binary function to successively combine the elements of a given vector and a possibly given initial value." 这使得创建给定值取决于先前值的向量变得更加容易。