# Passing an array of variables to a user-defined non-linear function

**URL:** <https://discourse.julialang.org/t/passing-an-array-of-variables-to-a-user-defined-non-linear-function/4132>\
**Category:** Optimization (Mathematical)\
**Tags:** question, jump\
**Created:** [June 7, 2017, 9:55am UTC](https://discourse.julialang.org/t/passing-an-array-of-variables-to-a-user-defined-non-linear-function/4132 "2017-06-07T09:55:29Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![Dan](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dan/32/42581_2.png) [@Dan](https://discourse.julialang.org/u/Dan)\
**Post date:** [June 7, 2017, 12:20pm UTC](https://discourse.julialang.org/t/passing-an-array-of-variables-to-a-user-defined-non-linear-function/4132/6 "2017-06-07T12:20:39Z")

</div>

Perhaps what you are looking for can be achieved with `@eval`. For example, taking `n = 3`, the code looks like:

```julia
m = Model(solver=IpoptSolver(print_level=0))
n=3
@variable(m, 0 <= x[1:n] <= 1)
f(x...) = rand()
df(g,x...) = g[:] = rand(n)
JuMP.register(m, :obj, n, f, df)

```

The problematic `@NLobjective` could be specialized for `n=3` as:

```julia
@NLobjective(m, Max, obj(x[1],x[2],x[3]))

```

and this would work. To make it work for other `n` defined at _runtime_, we could build-up this expression and `@eval` it, as follows:

```julia
@eval @NLobjective(m, Max, $(Expr(:call, :obj, [Expr(:ref,:x,i) for i=1:n]...)))

```

This works, but I’m not really sure, it’s the way to solve the underlying optimization problem.

---

_[View the full topic](https://discourse.julialang.org/t/passing-an-array-of-variables-to-a-user-defined-non-linear-function/4132)._
