我试图围绕CVXR编写一个包装器函数,这样'objective‘和'constraint’可以由一个函数传递。我使用以下示例:
示例:
x1 <- Variable(1) # a scalar
x2 <- Variable(1) # a scalar
objective <- Minimize( x1^2 + x2^2 )
constraints <- list(x1 <= 0, x1 + x2 == 0)
problem <- Problem(objective, constraints)
## Checking problem solution
solution <- solve(problem) 我的尝试到目前为止:
foo <- function(vars, const, obj) {
# for testing these values are passed inside
vars = c("x1", "x2")
obj = "x1^2 + x2^2"
const = "(x1 <= 0, x1 + x2 == 0)"
for(i in 1:length(vars)) {assign(vars[i], Variable(1, name = vars[i]))}
objective <- eval(paste("Minimize(", obj, ")"))
}问题:
目标变量不计算为x1^2 + x2^2,而是用引号计算。我试过了as.formula,eval,代用品等。
发布于 2020-07-18 10:21:45
也许您可以尝试使用parse和eval,如下所示
foo <- function(vars, const, obj) {
# for testing these values are passed inside
vars <- c("x1", "x2")
obj <- "x1^2 + x2^2"
const <- "(x1 <= 0, x1 + x2 == 0)"
for (i in 1:length(vars)) {
assign(vars[i], Variable(1, name = vars[i]))
}
objective <- eval(parse(text = paste("Minimize(", obj, ")")))
constraints <- eval(parse(text = paste("list", const)))
problem <- Problem(objective, constraints)
solve(problem)
}https://stackoverflow.com/questions/62967212
复制相似问题