# Integer variable as index of input matrix

**URL:** <https://discourse.julialang.org/t/integer-variable-as-index-of-input-matrix/24725>\
**Category:** Optimization (Mathematical)\
**Created:** [May 29, 2019, 11:29am UTC](https://discourse.julialang.org/t/integer-variable-as-index-of-input-matrix/24725 "2019-05-29T11:29:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Raminel](https://avatars.discourse-cdn.com/v4/letter/r/ea666f/32.png) [@Raminel](https://discourse.julialang.org/u/Raminel)\
**Post date:** [May 29, 2019, 11:29am UTC](https://discourse.julialang.org/t/integer-variable-as-index-of-input-matrix/24725/1 "2019-05-29T11:29:18Z")

</div>

Hi people,

Can I formulate an expression in Julia and use an integer variable as an index of an input matrix?

@variable(m, 1 \<= t[1:3, 1:3] \<= 8, Int)  
P = [90 80 60 70 50 30 10 0]

for i = 1:3  
for j = 1:3  
M[i,j] = P[t[i,j]] # M is a matrix 3x3 filled with P values based on t indices  
end  
end

and I am using M in an expression for optimization.

Thank you in advance!

---

<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:** [May 29, 2019, 1:27pm UTC](https://discourse.julialang.org/t/integer-variable-as-index-of-input-matrix/24725/2 "2019-05-29T13:27:08Z")

</div>

> Can I formulate an expression in Julia and use an integer variable as an index of an input matrix?

No.

But you can replicate the same thing using binary variables:

```Julia
model = Model()
@variable(model, z[i=1:3, j=1:3, t=1:8], Bin)
@variable(model, M[i=1:3, j=1:3])
@constraint(model, [i=1:3, j=1:3], M[i,j] == sum(P[k] * z[i,j,k] for k in 1:8))
@constraint(model, [i=1:3, j=1:3], sum(z[i,j,:]) == 1)

```

---

<div class="post-metadata">

**Author:** ![Raminel](https://avatars.discourse-cdn.com/v4/letter/r/ea666f/32.png) [@Raminel](https://discourse.julialang.org/u/Raminel)\
**Post date:** [May 29, 2019, 2:08pm UTC](https://discourse.julialang.org/t/integer-variable-as-index-of-input-matrix/24725/3 "2019-05-29T14:08:14Z")

</div>

Perfect! thank you!
