# Converting and applying MATLAB lsqnonlin function in Julia with multiple function arguments

I am trying to convert some MATLAB code into Julia. For the largest part this went pretty smooth, but I am now stuck with converting the MATLAB [lsqnonlin] function.

After scanning available options, I think that the [LsqFit.jl] package with its `curve_fit` function is the best way to go. Please correct me if I am wrong.

The original MATLAB code looks like this, where a function `calc_z` with given lower and upper boundaries (`lb` resp. `ub`) and initial guess `z` should yield optimal values of `z`. `**kwargs` contains all other function arguments required for `calc_z`.

``````z_opt = lsqnonlin(@calc_z, z, lb, ub, lsq_options, **kwargs)
``````

Internally, the function `calc_z` computes the error between initial `z` and observed values of z (`z_obs` which are part of `**kwargs`) plus two additional penalty terms which should be minimized to obtain the optimal values of z, `z_opt`.

The question now is how to correctly implement this in Julia. Thus far, I understand that I need something like

``````using LsqFit

fit = curve_fit(calz_z, xdata, ydata, p0, lower=lb, upper=ub)
# calz_z rewritten in Julia

z_opt = fit.param
``````

What is not clear to me is how to deal with the (kw)args required for `calc_z`. Do all `**kwargs` go into `p0`? And is `xdata` equivalent to `z` and `ydata` equivalent to `z_obs`?

It is also unclear to me whether Julia `curve_fit` implicitly computes the sum of squares of the components as `lsqnonlin` does in MATLAB?

Just pass a closure to capture any additional arguments: `curve_fit(x -> calz_z(x; kws...), ...)`