Claudio Moneo
Claudio Moneo

Reputation: 569

Optimizing in R with constraints

I have a function f of two variables which I want to minimize under the constraint x[1]+x[2]=1. Here,

f <- function(x){
y <- 4*sin(x[1])+3*cos(x[2])
return(y) 
}

I have read here that optim() does the work, but how do I include my constraint?

Upvotes: 0

Views: 127

Answers (1)

Darren Tsai
Darren Tsai

Reputation: 35649

After adding the constraint x[1] + x[2] = 1, the function becomes an univariate function and you can rewrite it as the following:

f <- function(x){
  4*sin(x) + 3*cos(1-x)
}

optimize() can be used on one-dimensional optimization.

opt <- optimize(0, c(0, 10))
opt

# $minimum
# [1] 4.468871
# 
# $objective
# [1] -6.722745

curve(f, 0, 10)
with(opt, points(minimum, objective, col = "red", pch = 16))

Upvotes: 1

Related Questions