写下独立的例程,以在solnl()

问题描述 投票:0回答:1

我需要找到一种编写独立例程的方法,以在Solnl()

中为最小化问题添加特定约束

以一个具体的例子,一个人有这个

##### for optimization library(MASS) library(NlcOptim) ############################## ###objective function to minimize objfun=function(x){ return(x[1]^2+x[2]^2+1) } ### our initial constraint to be improved constraint = function(x){ f = NULL f = rbind(f, x[2] - 2) return(list(ceq = f, c= NULL)) } #### solve now x0 = c(1,1) solnl(x0,objfun=objfun,confun=constraint)
我们要添加新约束

h(x) = x[1] - 1
使问题很容易解决。
我想拥有一个名为add_constraint(h)的函数,该函数将生成相同的可用输出AS

constraint = function(x){ f = NULL f = rbind(f, x[2] - 2) f = rbind(f,x[1] - 1 ) return(list(ceq = f, c= NULL)) }

我尝试了以下情况而没有成功
f = paste0("x[1] - 1")
h = paste0("x[2] - 2")

local = rbind(f,h)

# then the routine
add_constraint = function(local){

 function(x){
  f= NULL
  for( i in 1:2)
  f = rbind(f, local[i])
  return(list(ceq=f, c= NULL))
  }
 }

 constraint = add_constraint(local)

您可以在
body
r function constraints minimization
1个回答
0
投票
> constraint ## old FUN function(x) { f <- NULL f <- rbind(f, x[2] - 2) return(list(ceq=f, c=NULL)) } > add_constraint <- \(x) { + bd <- body(constraint) + rt <- bd[[length(bd)]] + bd[[length(bd)]] <- str2lang(x) + bd[[length(bd) + 1]] <- rt + body(constraint) <- bd + constraint + } > constraint <- add_constraint('f <- rbind(f, x[1] - 1)') > constraint ## new FUN function (x) { f <- NULL f <- rbind(f, x[2] - 2) f <- rbind(f, x[1] - 1) return(list(ceq = f, c = NULL)) }

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.