How to properly use the nlm function in R for minimizing functions?

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 11K views
the_dane
Messages
29
Reaction score
0
I try to find out how to minimize functions i R by using nlm function:
> f<-function(x,y){x^2+y^2+10-5*x-y}
> nlm(f,0.1,0.1)

That only gives me an estimate for x. How would write the code to get x and y?
 
Physics news on Phys.org
From
nlm(f, p, ..., hessian = FALSE, typsize = rep(1, length(p)),
fscale = 1, print.level = 0, ndigit = 12, gradtol = 1e-6,
stepmax = max(1000 * sqrt(sum((p/typsize)^2)), 1000),
steptol = 1e-6, iterlim = 100, check.analyticals = TRUE)

I gather p must be an array, not just a number like 0.1

(as becomes a good fortran programmer, I know nothing of R... :rolleyes: )
 
  • Like
Likes   Reactions: FactChecker
BvU said:
From
nlm(f, p, ..., hessian = FALSE, typsize = rep(1, length(p)),
fscale = 1, print.level = 0, ndigit = 12, gradtol = 1e-6,
stepmax = max(1000 * sqrt(sum((p/typsize)^2)), 1000),
steptol = 1e-6, iterlim = 100, check.analyticals = TRUE)

I gather p must be an array, not just a number like 0.1

(as becomes a good fortran programmer, I know nothing of R... :rolleyes: )
Also the independent input values of the function f must be an array x of dimension the same as p. (see https://stat.ethz.ch/R-manual/R-devel/library/stats/html/nlm.html )
 
Your code is calling nlm incorrectly. And the function is defined incorrectly for using nlm.

All the independent variables of f that nlm should manipulate should be in the array x and all their starting guess values should be in a matching array p. There are no constant parameters to pass to f.

Try something like this:
Code:
# Define a function of array x.
 f<-function(x){x[1]^2+x[2]^2+10-5*x[1]-x[2]}

# Initial guess values for x
 p = array( c( 1, 0), dim=c(2,1) )

# Call nlm
 ans <- nlm(f,p)

# print answer
 print(ans)
 
Last edited: