在CVXR中为目标函数传递字符串
我正试图围绕CVXR编写一个包装函数,以便函数可以传递“目标”和“约束”。我将使用以下示例: 示例:在CVXR中为目标函数传递字符串,r,cvxr,R,Cvxr,我正试图围绕CVXR编写一个包装函数,以便函数可以传递“目标”和“约束”。我将使用以下示例: 示例: 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(object
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也许您可以尝试使用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)
}
foo