Creating a sparse array with JuMP.QuadExpr elements

Hello all,

I’m very new to Julia and basically I want to define an empty sparse matrix of N x N and fill it up at certain points in the diagonal with just JuMP.QuadExpr elements.

I know I can do: A = spzeros(N, N) but trying to add a QuadExpr to an element results in the following error:

MethodError: Cannot convert an object of type GenericAffExpr{ComplexF64, VariableRef} to an object of type Float64

Any help is appreciated, thanks!

1 Like

Hi @JPG, welcome to the forum.

You need to use the spzeros(type, m, n) method:

help?> SparseArrays.spzeros
  spzeros([type,]m[,n])

  Create a sparse vector of length m or sparse matrix of size m x n. This sparse array will not contain any nonzero
  values. No storage will be allocated for nonzero values during construction. The type defaults to Float64 if not
  specified.

  Examples
  ≑≑≑≑≑≑≑≑≑≑

  julia> spzeros(3, 3)
  3Γ—3 SparseMatrixCSC{Float64, Int64} with 0 stored entries:
    β‹…    β‹…    β‹…
    β‹…    β‹…    β‹…
    β‹…    β‹…    β‹…
  
  julia> spzeros(Float32, 4)
  4-element SparseVector{Float32, Int64} with 0 stored entries

Here’s an example:

julia> Q = SparseArrays.spzeros(QuadExpr, 3, 3)
3Γ—3 SparseArrays.SparseMatrixCSC{QuadExpr, Int64} with 0 stored entries:
 β‹…  β‹…  β‹…
 β‹…  β‹…  β‹…
 β‹…  β‹…  β‹…

julia> model = Model();

julia> @variable(model, x)
x

julia> Q[1, 1] = 2 * x^2 + 1
2 xΒ² + 1

julia> Q
3Γ—3 SparseArrays.SparseMatrixCSC{QuadExpr, Int64} with 1 stored entry:
 2 xΒ² + 1  β‹…  β‹…
 β‹…         β‹…  β‹…
 β‹…         β‹…  β‹…

But it looks like you might have a complex-valued affine expression, not a quadratic expression?

In that case, you’d need

julia> Q = SparseArrays.spzeros(GenericAffExpr{ComplexF64, VariableRef}, 3, 3)
3Γ—3 SparseArrays.SparseMatrixCSC{GenericAffExpr{ComplexF64, VariableRef}, Int64} with 0 stored entries:
 β‹…  β‹…  β‹…
 β‹…  β‹…  β‹…
 β‹…  β‹…  β‹…

julia> Q[1, 1] = (2.0 + 3.0im) * x
(2 + 3im) x

julia> Q
3Γ—3 SparseArrays.SparseMatrixCSC{GenericAffExpr{ComplexF64, VariableRef}, Int64} with 1 stored entry:
 (2 + 3im) x  β‹…  β‹…
 β‹…            β‹…  β‹…
 β‹…            β‹…  β‹…
1 Like

Thank you very much, that worked perfectly!

As a side note, I do have complex-valued affine expressions and complex-value quadratic expressions, but your solution worked for both, I simply replaced the GenericAffExpr with GenericQuadExpr, for my other cases.

1 Like