Code:
function b̂ₜfunc(
x̂ₜ₊₁::AbstractVector,
Σ̂ₜ₊₁::AbstractMatrix,
γ::AbstractFloat,
ξ::AbstractFloat,
b̂ₜ::AbstractVector
)
n_assets = length(x̂ₜ₊₁)
model = Model(optimizer_with_attributes(Ipopt.Optimizer, "print_level" => 0))
@variable(model, c[1:n_assets])
@constraint(model, sum(c)==0)
@NLobjective(model, Min, γ*c'*Σ̂ₜ₊₁*(c')' + c'*((2γ*b̂ₜ'*Σ̂ₜ₊₁)'-x̂ₜ₊₁) + ξ*sum(abs(item) for item in c))
optimize!(model)
return value.(c)
end
Reproducible example:
x̂ₜ₊₁ = [0.9884, 1.02564, 1.01561];
Σ̂ₜ₊₁ = rand(3, 3);
gam = 0.02;
kasi = 0.03;
b = [0.5, 0.1, 0.4];
b̂ₜfunc(x̂ₜ₊₁, Σ̂ₜ₊₁, gam, kasi, b)
Throws:
ERROR: Unexpected array VariableRef[c[1] c[2] c[3]] in nonlinear expression. Nonlinear expressions may contain only scalar expressions.
Other variants that I’ve tried:
@NLobjective(model, Min, sum((γ*c'*Σ̂ₜ₊₁)[item]*c[item] for item=1:n_assets) + c'*((2γ*b̂ₜ'*Σ̂ₜ₊₁)'-x̂ₜ₊₁) + ξ*sum(abs(item) for item in c))
# And
@NLobjective(model, Min, γ*c'*Σ̂ₜ₊₁*(c')' + sum(c[item]*((2γ*b̂ₜ'*Σ̂ₜ₊₁)'-x̂ₜ₊₁)[item] for item=1:n_assets) + ξ*sum(abs(item) for item in c))
# And
@NLobjective(model, Min, γ*c'*Σ̂ₜ₊₁*c + only(c'*((2γ*b̂ₜ'*Σ̂ₜ₊₁)'-x̂ₜ₊₁)) + ξ*sum(abs(item) for item in c))
Throws the same error.
When I try @NLobjective(model, Min, γ*c'*Σ̂ₜ₊₁*c)
I get the same error. Hence, the problem is with the matrix multiplication. I do not understand. This is the same as this example. Why it does not work in my case? Got it. Because I used @NLobjective
.