From 9562a7b94f0b28e3a8d8ee2dc7c646100acaf8bb Mon Sep 17 00:00:00 2001 From: Joaquim Dias Garcia Date: Wed, 23 Oct 2024 18:03:47 -0300 Subject: [PATCH] Clarify usage of `add_to_expression!` in docs (#3859) --- docs/src/manual/expressions.md | 27 +++++++++++++++++++++++++++ src/aff_expr.jl | 24 ++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/docs/src/manual/expressions.md b/docs/src/manual/expressions.md index 59944f0c24a..93cd5815c35 100644 --- a/docs/src/manual/expressions.md +++ b/docs/src/manual/expressions.md @@ -126,6 +126,33 @@ julia> add_to_expression!(ex, 1.0, y) 2 x + y - 1 ``` +[`add_to_expression!`](@ref) can also be used to sum expressions +in-place: + +```jldoctest +julia> model = Model(); + +julia> @variable(model, x[1:2]) +2-element Vector{VariableRef}: + x[1] + x[2] + +julia> @expression(model, ex1, sum(x)) +x[1] + x[2] + +julia> @expression(model, ex2, 2 * sum(x)) +2 x[1] + 2 x[2] + +julia> add_to_expression!(ex1, ex2) +3 x[1] + 3 x[2] + +julia> ex1 +3 x[1] + 3 x[2] + +julia> ex2 +2 x[1] + 2 x[2] +``` + !!! warning Read the section [Initializing arrays](@ref) for some cases to be careful about when using [`add_to_expression!`](@ref). diff --git a/src/aff_expr.jl b/src/aff_expr.jl index 2e49a418139..abfdba2f1d2 100644 --- a/src/aff_expr.jl +++ b/src/aff_expr.jl @@ -514,6 +514,30 @@ julia> add_to_expression!(expr, 3, x) julia> expr 4 x + 2 ``` + +```jldoctest +julia> model = Model(); + +julia> @variable(model, x[1:2]) +2-element Vector{VariableRef}: + x[1] + x[2] + +julia> @expression(model, ex1, sum(x)) +x[1] + x[2] + +julia> @expression(model, ex2, 2 * sum(x)) +2 x[1] + 2 x[2] + +julia> add_to_expression!(ex1, ex2) +3 x[1] + 3 x[2] + +julia> ex1 +3 x[1] + 3 x[2] + +julia> ex2 +2 x[1] + 2 x[2] +``` """ function add_to_expression! end