diff --git a/src/operators.jl b/src/operators.jl index 5310234ddc0..608dacc5028 100644 --- a/src/operators.jl +++ b/src/operators.jl @@ -451,3 +451,23 @@ function LinearAlgebra.issymmetric(x::Matrix{T}) where {T<:_JuMPTypes} end return true end + +function Base.:+(A::AbstractMatrix, x::AbstractJuMPScalar) + return error( + "Addition between a Matrix and a JuMP variable is not supported: instead of `A + x`, " * + "do `A .+ x` for element-wise addition, or if you are modifying the diagonal entries of the matrix " * + "do `A + x * LinearAlgebra.I(n)`, where `n` is the diagonal length.", + ) +end + +Base.:+(x::AbstractJuMPScalar, A::AbstractMatrix) = A + x + +function Base.:-(A::AbstractMatrix, x::AbstractJuMPScalar) + return error( + "Subtraction between a Matrix and a JuMP variable is not supported: instead of `A - x`, " * + "do `A .- x` for element-wise subtraction, or if you are modifying the diagonal entries of the matrix " * + "do `A - x * LinearAlgebra.I(n)`, where `n` is the diagonal length.", + ) +end + +Base.:-(x::AbstractJuMPScalar, A::AbstractMatrix) = A - x diff --git a/test/test_operator.jl b/test/test_operator.jl index 967fb8b666d..4f43a05891a 100644 --- a/test/test_operator.jl +++ b/test/test_operator.jl @@ -625,4 +625,43 @@ function test_complex_pow() return end +function test_matrix_abstractscalar_add() + model = Model() + @variable(model, x) + A = rand(Float64, 2, 2) + @test_throws( + ErrorException( + "Addition between a Matrix and a JuMP variable is not supported: instead of `A + x`, " * + "do `A .+ x` for element-wise addition, or if you are modifying the diagonal entries of the matrix " * + "do `A + x * LinearAlgebra.I(n)`, where `n` is the diagonal length.", + ), + A + x + ), + @test_throws( + ErrorException( + "Addition between a Matrix and a JuMP variable is not supported: instead of `A + x`, " * + "do `A .+ x` for element-wise addition, or if you are modifying the diagonal entries of the matrix " * + "do `A + x * LinearAlgebra.I(n)`, where `n` is the diagonal length.", + ), + x + A + ), + @test_throws( + ErrorException( + "Subtraction between a Matrix and a JuMP variable is not supported: instead of `A - x`, " * + "do `A .- x` for element-wise subtraction, or if you are modifying the diagonal entries of the matrix " * + "do `A - x * LinearAlgebra.I(n)`, where `n` is the diagonal length.", + ), + A - x + ), + @test_throws( + ErrorException( + "Subtraction between a Matrix and a JuMP variable is not supported: instead of `A - x`, " * + "do `A .- x` for element-wise subtraction, or if you are modifying the diagonal entries of the matrix " * + "do `A - x * LinearAlgebra.I(n)`, where `n` is the diagonal length.", + ), + x - A + ), + return +end + end