Absolute value of matrix

How to define the absolute value of all elements in the matrix?

using JuMP,Gurobi

 model = Model(Gurobi.Optimizer);
 @variable(model, 2 <= a[1:T,1:3]<= 2.5, Int)

for i = 1:3
        for t = 2:T
            @constraint(model, WES_BT[t,i] == WES_BT[t-1,i]/0.98 )

@constraint(model,0 .<=PMT .<= 60)

term_status = JuMP.termination_status(model)
   primal_status = JuMP.primal_status(model)
   is_optimal = term_status == MOI.OPTIMAL

I try to use@NLobjective
@NLobjective(model,Min,sum(abs(0.3PMT[i,j]+0.3a[i,j] for i in 1:T j in 1:3)))
The following error still occurs, I don’t know how to change it

LoadError: sum() can appear in nonlinear expressions  only if the argument is a generator statement, for example, sum(x[i] for i in 1:N).
 [1] error(::String) at .\error.jl:33
 [2] top-level scope at C:\Users\61940\.juliapro\JuliaPro_v1.4.2-1\packages\JuMP\YXK4e\src\parse_nlp.jl:247
 [3] top-level scope at C:\Users\61940\.juliapro\JuliaPro_v1.4.2-1\packages\JuMP\YXK4e\src\macros.jl:1328
in expression starting at E:\Julia程序\lizi.jl:23

Have you tried sum(abs(0.3PMT[i,j]+0.3a[i,j]) for i in 1:T j in 1:3) ? I am not proficient in JuMP but the error suggests that sum should take generator instead of the abs.

I’ve tried, but it doesn’t seem right.

I’m very sorry to ask you again!
In JuMP, how to add absolute value to the objective function, I only know that because of the absolute value, it becomes nonlinear and needs to be used @NLobjective
But how to realize the sum of matrix?

What you want is to broadcast the abs function to individual elements:


I changed it according to what you said, but the error is still the same```

LoadError:sum() can appear in nonlinear expressions only if the argument is a generator statement, for example, sum(x[i] for i in 1:N).

No need for @NLobjective,you can formulate this as a linear program:

using JuMP
T = 24
model = Model()
@variables(model, begin
    2 <= a[1:T, 1:3]<= 2.5, Int
    0 <= PMT[1:T, 1:3] <= 60
    0 <= WES_BT[1:T, 1:3] <= 20
    abs_pmt[1:T, 1:3] >= 0
@constraints(model, begin
    [i=1:3, t = 2:T], WES_BT[t, i] == WES_BT[t-1, i] / 0.98
    abs_pmt .>= 0.3 .* PMT + 0.3 .* a
    abs_pmt .>= -(0.3 .* PMT + 0.3 .* a)
@objective(model, Min, sum(abs_pmt))
1 Like

This transformation is so ingenious!
But I still want to ask one more question: is it not easy to realize my previous idea of using for loops in objective

If it is a nonlinear objective function (for example, if there is a matrix summation of the square term in the objective function), then how to realize sum () I am more curious

As stated in the error message, you need to write @NLobjective(model, Min, sum(abs(PMT[t,i]) for t = 1:T, i=1:3)).

1 Like

The Mosek modeling cookbook has lots of interesting transformations: https://docs.mosek.com/modeling-cookbook/linear.html#absolute-value

Your answer is always to the point!
I know that most solvers can’t solve the NLP problem. Thank you. I’ll take a look at it.