Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

How to use nlm function in R

  1. Nov 15, 2016 #1
    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?
  2. jcsd
  3. Nov 16, 2016 #2


    User Avatar
    Science Advisor
    Homework Helper
    2017 Award

    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: )
  4. Nov 16, 2016 #3


    User Avatar
    Science Advisor
    Gold Member
    2017 Award

    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 )
  5. Nov 16, 2016 #4


    User Avatar
    Science Advisor
    Gold Member
    2017 Award

    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 (Text):

    # Define a function of array x.

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

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

    # print answer

    Last edited: Nov 16, 2016
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted