Constrained optimization of a 2 function of two variable

Hello everyone, I have to solve a very difficult problem in R.
I have to maximise the function f(x,y) = x^2 +xy+y^2+3y+2 and I have two constraints:

  • I have to maximise inside the parabola y=x^2-2
  • and I have to respect the constraint y<= 1

I would solve it like this, but I don’t know how to write the matrix A and the vector b.
f ← function (xx,y) xx^2 + xxy +y^2 +3y +2
f

fv ← function (x) f(x[1],x[2])
fv

xx ← seq (-5,5,len=51)
y ← seq (-5,5,len=51)
z = outer (xx,y,f)
image (xx,y,z)
contour (xx,y,z,add=T)

curve (x^2 -2 ,-5,5,add=T)
abline (h=1)

constrOptim (c(0,0),fv,NULL,A,bcontrol=list (fnscale=-1))

I have the exam on Monday, so please help me this weekend.
Thank you in advance,
good by and sorry for my bad english.

Hello Martin,
In R, you can solve this optimization problem using the constrOptim function.

Here’s the code to solve the problem:

f <- function(xx, y) xx^2 + xx * y + y^2 + 3 * y + 2

fv <- function(x) f(x[1], x[2])

xx <- seq(-5, 5, len = 51)
y <- seq(-5, 5, len = 51)

z <- outer(xx, y, f)
image(xx, y, z)
contour(xx, y, z, add = TRUE)

curve(x^2 - 2, -5, 5, add = TRUE)
abline(h = 1)

A <- matrix(c(-1, 2, 0, 1), nrow = 2, byrow = TRUE)
b <- c(-2, 1)

result <- constrOptim(c(0,0), fv, NULL, A, b, control = list(fnscale = -1))

print(result$par)

The optimization problem consists of maximizing the function f(x,y) = x^2 + xy + y^2 + 3y + 2 subject to two constraints: y <= 1 and y = x^2 - 2. The constraints are specified using the matrix A and the vector b. The A matrix has two rows and two columns, where the first row represents the constraint y <= 1 and the second row represents the constraint y = x^2 - 2. The b vector has two elements, where the first element represents the right-hand side of the constraint y <= 1 and the second element represents the right-hand side of the constraint y = x^2 - 2.

The result of the optimization is stored in the result object and can be accessed using the result$par element