# 1-Variable Scalar-Valued Function f(x)
f<-function(x) log(x)-x^2

# 2-variable scalar-valued function g(x):
g<-function(x) {
  x1<-x[1]
  x2<-x[2]
  return((x1^2+x2-11)^2+(x1+x2^2-7)^2)
}

# find maximum of f(x) at x=sqrt(0.5):
# check: f1=0 and f2<0 @
fn<-function(x) -f(x)      # negative f, to find minimum of fn
nlm(fn,1)
op1<-optim(1,f,method="BFGS",control=list(fnscale=-1,trace=10))

# find 4 minima of g(x,y) at: g1=0 0, g2= positive definite
# (3,2), (3.5844,-1.8481), (-3.7793,-3.2832), (-2.8051,3.1313)
# there is 1 maximum: (-0.27084,-0.92304) with f=181.62
# saddle points: (0.08668,2.88430), (3.38520,0.07358), (-3.07300,-0.08135)
nlm(g,c(2,3))
nlm(g,c(2,-3))
nlm(g,c(-2,3))
nlm(g,c(-2,-3))

# find maximum of g(x)
gn<-function(x) -g(x)      # negative g, to find minimum of gn
nlm(gn,c(-0.25,-1))
optim(c(-0.25,-1),g,method="BFGS",control=list(fnscale=-1))
      
