Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to optimize a simple function with optimize()?

    I am trying to run a maximum-likelihood estimation in Mata using optimize(). However, I cannot get the maximum value of even quite simple functions, so there must be a programming error with my code. I have produced a minimum working example below, where I replaced my original function with a simple x^2, just to understand what is going on:


    Code:
    mata
    mata clear
    end
    
    
    
    
    mata
    
    function logit_mata2(costs_guess)
    {
    printf("control")
    ll = -(costs_guess)^2
    
    return(ll)
    
    
    }
    
    logit_mata2(10)
    
    S2 = optimize_init()
    optimize_init_evaluator(S2, &logit_mata2())
    optimize_init_params(S2, 10 )
    result = optimize(S2)
    
    end
    I get the following error, which I have difficulty making any sense of:

    logit_mata2(): 3001 expected 1 arguments but received 5
    opt__calluser0_d(): - function returned error
    opt__d0_calluser(): - function returned error
    deriv__call1user_d(): - function returned error
    _deriv__compute_value(): - function returned error
    _deriv(): - function returned error
    opt__eval_nr_d0(): - function returned error
    opt__eval(): - function returned error
    opt__looputil_iter0_common(): - function returned error
    opt__looputil_iter0_nr(): - function returned error
    opt__loop_nr(): - function returned error
    opt__loop(): - function returned error
    optimize(): - function returned error
    <istmt>: - function returned error
    In my mind, I have not declared any arguments exept the one parameter for which I would like the optimal value, so I do not understand what this represents

    Thank you in advance!

    Best,

    Richard
    Last edited by Richard Braeuer; 25 Jan 2024, 16:28. Reason: added tags

  • #2
    HI -- So I think the function you want to optimize has to have a specific set of input parameters and has to be a -void- function. Here is some code just recently used to determine the shape and scale of the inverse gamma distribution, where I want to know the values of those parameters that yield prespecified [by me] quantiles.

    ----

    // Find needed shape and scale
    void fnToMax(todo, p, v, g, H)
    {
    // Solve to get prUp=0.95 and prLo=0.05
    // 5th percentile should be 1/19
    // 95th percentile should be 3
    // p[1]=shape and p[2]=scale
    prLo=1-gammap(p[1],p[2]/(1/19))
    prUp=1-gammap(p[1],p[2]/3)
    v=-((prUp-.95)^2+(prLo-0.05)^2)
    }
    S = optimize_init()
    optimize_init_evaluator(S, &fnToMax())
    optimize_init_params(S,(.1,0.5))
    gamParms = optimize(S)
    gamParms


    ----

    Comment

    Working...
    X