2016-01-06 67 views
0

我想提出的優化算法slsqp其中目標函數取決於兩個參數,一個循環 - 第二個參數是循環的變量:R:優化算法SLSQP

library(nloptr) 

example <- function(w, j){ return(sum((w + j)^2)) } 

heq_fun是平等的約束功能上寬:

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

嘗試在循環中創建一個新函數,只在一個參數上使用白色。這應該有幫助

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)) 
}