# Show and use expressions

I am having a trouble 1- printing the expression Ad, and 2- using it in a nonlinear constraint.

using LinearAlgebra
using JuMP
model = Model( )

n = 8
u = ones(n)

@variable(model, A[1:n, 1:n], Symmetric)
A = LowerTriangular(A)
@variable(model, b[1:n])

d = @expression(model, A * u)
@expression(model, Ad, (sum(A[i,j]*d[j] for j in 1:i-1) for i in 1:n) )
@NLconstraint(model, sum(b[i]*Ad[i] for i in 1:n) == 1/3);

For the former, when I type Ad in the prompt I get

Base.Generator{UnitRange{Int64}, var"#37#39"}(var"#37#39"(), 1:8)

which I don’t know what it means. For the constraint it gives this error

MethodError: no method matching getindex(::Base.Generator{UnitRange{Int64}, var"#37#39"}, ::Int64)

Stacktrace:
[1] macro expansion
@ ~/.julia/packages/JuMP/60Bnj/src/macros.jl:1974 [inlined]
[2] top-level scope
@ ./In[4]:15
[3] eval
@ ./boot.jl:373 [inlined]
[4] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)


You didn’t have the syntax for Ad quite right. It needs to be:

@expression(model, Ad[i=1:n], sum(A[i,j]*d[j] for j in 1:i-1))


Here’s how I’d write your model:

using JuMP
import LinearAlgebra

n = 8
model = Model()
@variable(model, A[1:n, 1:n], Symmetric)
@variable(model, b[1:n])
A = LinearAlgebra.LowerTriangular(A)
u = ones(n)
d = @expression(model, A * u)
@expression(model, Ad[i=1:n], sum(A[i,j]*d[j] for j in 1:i-1))
@NLconstraint(model, sum(b[i] * Ad[i] for i in 1:n) == 1 / 3)