我有这个公式,我想在R。
中实现
这是双循环方式:
munew = 0
mu_normalizer = 0
for (j in 1:dim(x)[2] ) {
for (i in 1:dim(x)[1] ) {
munew = munew + (x[i,j]/(sigma_2[j] *omega_2[i]))
}}
for (j in 1:dim(x)[2] ) {
for (i in 1:dim(x)[1] ) {
mu_normalizer = mu_normalizer + (1/(sigma_2[j] *omega_2[i]))
}}
munew = munew/mu_normalizer
其中sigma_2和omega_2分别为sigma ^ 2和omega ^ 2.
我在R中实现这个的最快方法是什么?
答案 0 :(得分:3)
或许outer
(或其%o%
)有帮助:
x = matrix(sample(1:3, 20, T), 5)
sigma_2 = runif(4)
omega_2 = runif(5)
munew = 0
mu_normalizer = 0
for (j in 1:dim(x)[2] ) {
for (i in 1:dim(x)[1] ) {
munew = munew + (x[i,j]/(sigma_2[j] *omega_2[i]))
}}
munew
#[1] 445.5648
sum(x / (omega_2 %o% sigma_2))
#[1] 445.5648
for (j in 1:dim(x)[2] ) {
for (i in 1:dim(x)[1] ) {
mu_normalizer = mu_normalizer + (1/(sigma_2[j] *omega_2[i]))
}}
mu_normalizer
#[1] 201.6099
sum(1 / (omega_2 %o% sigma_2))
#[1] 201.6099
munew/mu_normalizer
#[1] 2.210034
sum(x / (omega_2 %o% sigma_2)) / sum(1 / (omega_2 %o% sigma_2)) #this is the actual answer
#[1] 2.210034