我想在优化算法slsqp上进行循环,其中目标函数依赖于两个参数 - 第二个参数是循环变量:
library(nloptr)
example <- function(w, j){ return(sum((w + j)^2)) }
heq_fun是w:
上的等式约束函数heq_fun<-function(w){
Mat <- rbind(rep(1,length(w)))
sum <- Mat %*% w
return(sum-1)}
循环:
sol_list <- list()
for(j in 1:5){
sol_list[[j]]<-slsqp(fund_weights, fn = example, gr = NULL, lower = rep(0, 16),
upper = rep(1, 16), hin = NULL, hinjac = NULL, heq = heq_fun,
heqjac = NULL, nl.info = FALSE, control =list(stopval = -Inf,
xtol_rel = 1e-9, maxeval = 100000))
}
我明白了:
Error in fun(x, ...) : argument "j" is missing, with no default
算法不明白最小化函数的第二个参数也是循环变量......
你能帮我吗?
答案 0 :(得分:0)
尝试在循环中创建一个新函数,仅在一个参数上创建。这应该有帮助
sol_list <- list()
for(j in 1:5){
example <- function(w){ return(sum((w + j)^2)) }
sol_list[[j]]<-slsqp(fund_weights, fn = example, gr = NULL, lower = rep(0,16),
upper = rep(1, 16), hin = NULL, hinjac = NULL, heq = heq_fun,
heqjac = NULL, nl.info = FALSE, control =list(stopval = -Inf,
xtol_rel = 1e-9, maxeval = 100000))
}