# DiffEqDiffTools - addtional variables in objective function

**URL:** <https://discourse.julialang.org/t/diffeqdifftools-addtional-variables-in-objective-function/10965>\
**Category:** General Usage\
**Tags:** question, diffeq\
**Created:** [May 17, 2018, 7:41pm UTC](https://discourse.julialang.org/t/diffeqdifftools-addtional-variables-in-objective-function/10965 "2018-05-17T19:41:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![waldoc](https://avatars.discourse-cdn.com/v4/letter/w/ce7236/32.png) [@waldoc](https://discourse.julialang.org/u/waldoc)\
**Post date:** [May 17, 2018, 7:41pm UTC](https://discourse.julialang.org/t/diffeqdifftools-addtional-variables-in-objective-function/10965/1 "2018-05-17T19:41:31Z")

</div>

Hi, I have found DiffEqDiffTools.finite\_difference\_jacobian to be quite useful, thanks to the devs 😄

I just have a question regarding passing additional variables in the objective function. The standard format would be:

```julia
function f(fvec,x)
    fvec[1] = (x[1]+3)*(x[2]^3-7)+18
    fvec[2] = sin(x[2]*exp(x[1])-1)
end

```

which would work with e.g.:

```julia
J = DiffEqDiffTools.finite_difference_jacobian(f, x)

```

however, what if I needed to pass additional variables into the function:

```julia
function f(fvec,x,constants)
    fvec[1] = (x[1]+3)*(x[2]^3-7)+18 + constants[1]*x[1] + constants[2]
    fvec[2] = sin(x[2]*exp(x[1])-1) - constants[3]
end

```

This function definition does not work with DiffEqDiffTools.finite\_difference\_jacobian since it expects f((::Array{Float64,1}, ::Array{Float64,1})). In the above case without making “constants” global, is there a way to pass the variable to the function and still be compatible with DiffEqDiffTools.finite\_difference\_jacobian? Note, in my actual usage case there are a large number of structs being passed into the objective function and since it is computing a relatively large Jacobian the function calls need to be as efficient as possible.

Thanks

---

<div class="post-metadata">

**Author:** ![ChrisRackauckas](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/chrisrackauckas/32/77_2.png) [@ChrisRackauckas](https://discourse.julialang.org/u/ChrisRackauckas)\
**Post date:** [May 18, 2018, 12:10am UTC](https://discourse.julialang.org/t/diffeqdifftools-addtional-variables-in-objective-function/10965/2 "2018-05-18T00:10:38Z")

</div>

Use a closure:

```julia
J = DiffEqDiffTools.finite_difference_jacobian((fvec,x)->f(fvec,x,constants), x)

```

---

<div class="post-metadata">

**Author:** ![waldoc](https://avatars.discourse-cdn.com/v4/letter/w/ce7236/32.png) [@waldoc](https://discourse.julialang.org/u/waldoc)\
**Post date:** [May 18, 2018, 4:38am UTC](https://discourse.julialang.org/t/diffeqdifftools-addtional-variables-in-objective-function/10965/3 "2018-05-18T04:38:07Z")

</div>

Thanks a lot for the answer (to a probably a trivial question)
