# Constructing a sparse variable for optimization

**URL:** <https://discourse.julialang.org/t/constructing-a-sparse-variable-for-optimization/109269>\
**Category:** Optimization (Mathematical)\
**Tags:** question, jump\
**Created:** [January 25, 2024, 6:03pm UTC](https://discourse.julialang.org/t/constructing-a-sparse-variable-for-optimization/109269 "2024-01-25T18:03:43Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![legio](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/legio/32/206356_2.png) [@legio](https://discourse.julialang.org/u/legio)\
**Post date:** [January 25, 2024, 6:03pm UTC](https://discourse.julialang.org/t/constructing-a-sparse-variable-for-optimization/109269/1 "2024-01-25T18:03:43Z")

</div>

I want to optimize over a matrix X.

While I specify in my model constraints the indices at which X must be zero (according to the specifications I provide in a binary matrix A):

```julia
@variable(model, X[1:n_rows, 1:n_cols])
set_lower_bound.(X, zeros(n_rows, n_cols))
set_upper_bound.(X, ones(n_rows, n_cols))
@constraint(model, X .<= A')

```

I’m wondering if there’s a better alternative I could use – like constructing X as a sparse matrix variable or reformulating my constraints – to help the JuMP model recognize that it does not need to consider the zero-constrained entries of X as variables over which it should optimize, with the hope that it makes the model more efficient.

I’m new to julia, so any insight is super appreciated : )

---

<div class="post-metadata">

**Author:** ![odow](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/odow/32/28685_2.png) [@odow](https://discourse.julialang.org/u/odow)\
**Post date:** [January 25, 2024, 8:15pm UTC](https://discourse.julialang.org/t/constructing-a-sparse-variable-for-optimization/109269/2 "2024-01-25T20:15:39Z")

</div>

> [@legio](#):
>
> `@variable(model, X[1:n_rows, 1:n_cols])`

I would do;

```julia
@variable(model, 0 <= X[i in 1:n_rows, j in 1:n_cols] <= A[j, i])

```

If the matrix is very sparse, you might also consider creating a `SparseAxisArray` like:

```julia
@variable(model, 0 <= X[i in 1:n_rows, j in 1:n_cols; A[j, i] == 1] <= 1)

```

but this has some limitations because it doesn’t act like a true sparse array (you can’t do linear algebra with it).
