Update input argument in each Optim.jl iteration

b is already global in global scope (outside of the function), you need to declare it global inside the function, like so

function log_like(a)
   b_sol = contraction_mapper(a, b) # find fixed point b_sol given guess of a and b
   lnl = -sum(log.(prob(a, b_sol)), dims=1); # log likelihood given b_sol and a

   global b
   b = b_sol;  # update b guess with contraction mapping from last round
   return lnl
end

To make it performant, I would declare

const b = copy(b0)

function log_like(a)
   b_sol = contraction_mapper(a, b) # find fixed point b_sol given guess of a and b
   lnl = -sum(log.(prob(a, b_sol)), dims=1); # log likelihood given b_sol and a

   global b
   b .= b_sol;  # update b guess with contraction mapping from last round
   return lnl
end

i.e., make b into a const variable and then update b in-palce using .=.

Global non-constant variables have big performance impacts in julia, but you can easily use a const global here which have no performance impacts

1 Like