【发布时间】:2019-10-23 05:26:50
【问题描述】:
我在下面定义了一个名为 algor 的函数,它从 MATLAB 转换为 R。为了使函数更快,我第一次使用 foreach 构造。我有完整的功能代码如下:
library("ramify")
library("foreach")
algor <- function (vc) {
# initialize A, ybar, and Ia
A <- 0
ybar <- 0
Ia <- 0
# x is the first column of vc
x <- vc[, 1, drop = FALSE]
# y is the second column of vc
y <- vc[, 2, drop = FALSE]
# n is the length of x
n <- length(x)
foreach(i = 1:(n-1), .combine = 'c', .export = c("A", "ybar", "Ia", "x", "y")) %do% {
A <- A + 0.5 * (x[i] - x[i+1]) * (y[i] + y[i+1])
ybar <- ybar + (1 / 6) * (x[i] - x[i+1]) * (y[i] ^ 2 + y[i] * y[i+1] + y[i+1] ^ 2)
Ia <- Ia + (1 / 12) * (x[i] - x[i+1]) * (y[i] ^ 3 + y[i] ^ 2 * y[i+1] + y[i] * y[i+1] ^ 2 + y[i+1] ^ 3)
}
props <- mat("A, Ia, ybar", eval = TRUE)
return(props)
}
inner <- mat("0, 300; 300, 300; 300, 695; 0, 695; 0, 300")
algor(inner)
虽然我导出了 A、ybar、Ia、x 和 y,但我收到一个错误,指出找不到对象 A,如下所示:
Error in eval(parse(text = paste0("c(", paste0(char_vals, collapse = ","), :
object 'A' not found
Called from: eval(parse(text = paste0("c(", paste0(char_vals, collapse = ","),
")")))
如何让foreach 识别定义的对象:A、ybar、Ia、x 和 y?
谢谢。
【问题讨论】: