optim error message

This looks quite basic, and I have absolutely no idea why it doesn't work. :frowning:

f <- function(x, y){x^2 + 2*y^2 + sin(2*x + y^2)}

# some verification (looks fine)


# plotted a contour graph (still looks fine)

xgrid <- seq(-3, 3, .01)
ygrid <- seq(-3, 3, .01)
z <- outer(xgrid, ygrid, f)
contour(xgrid, ygrid, z, nlevels = 20)

# optim gives error message

optim(c(0, 0), f)

The optim command produces:

"Error in fn(par, ...) : argument "y" is missing, with no default"

optim want parameters passed in as a vector, ufortunately it means rewriting your function so that it pulls out x and y from the first and second positions of a generic double vector like so

# parm[1] will be x and parm[2] will be y
f <- function(parm){parm[1]^2 + 2*parm[2]^2 + sin(2*parm[1] + parm[2]^2)}

# some verification (looks fine)



This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.