I am very new to Julia. I wish to obtain the indices of my output that are non-zero
1 Like
Welcome to julia!, if you need only the indices, the following function can help you.
indices = findall(!iszero,-2:2) # [-2,-1,1,2]
there are some things going on with this
-
findall
acepts a function and a iterable container -
iszero(x)
is a function that givestrue
if x is zero -
!
is a negation operator, and it works on functions too, when those functions give a boolean as output -
!iszero(x)
then is a function that givestrue
if x is not zero, its not necessary to define a auxiliary function, is enough to write!iszero
!
Thanks for the response. Sorry I think I meant the key. In this image I have an example. If i input var1 I would like to retain [2.0,5.0,2.0,5.0] but not the others…
var1 is a DenseAxisArray
mmm, i had never worked with DenseAxisArray, can you post the code necessary to generate that array?
You’re probably looking for something like:
julia> using JuMP
julia> using Gurobi
julia> model = Model(with_optimizer(Gurobi.Optimizer, OutputFlag=0));
Academic license - for non-commercial use only
julia> @variable(model, x[1:2, 1:3], Bin)
2Ă—3 Array{VariableRef,2}:
x[1,1] x[1,2] x[1,3]
x[2,1] x[2,2] x[2,3]
julia> @objective(model, Min, sum((-1)^(i + j) * x[i, j] for i in 1:2, j in 1:3))
x[1,1] - x[1,2] + x[1,3] - x[2,1] + x[2,2] - x[2,3]
julia> optimize!(model)
Academic license - for non-commercial use only
julia> x_val = value.(x)
2Ă—3 Array{Float64,2}:
0.0 1.0 0.0
1.0 0.0 1.0
julia> x[x_val .> 0.5]
3-element Array{VariableRef,1}:
x[2,1]
x[1,2]
x[2,3]
2 Likes
using JuMP
using Gurobi
m=Model(with_optimizer(Gurobi.Optimizer,OutputFlag=0))
@variable(m,z[i_1=2:m1,i_2=i_1:m1,j_1=2:m2,j_2=j_1:m2],Bin)
Thank you! I tried this but I get an error because z is a DenseAxisArray and this is not supported.
So what about something like
using JuMP, Gurobi
m1 = 4
m2 = 4
m=Model(with_optimizer(Gurobi.Optimizer,OutputFlag=0))
@variable(m,z[i_1=2:m1,i_2=i_1:m1,j_1=2:m2,j_2=j_1:m2],Bin)
optimize!(model)
z_val = value.(z)
on_variables = [key for key in eachindex(z) if z_val[key] > 0.5]
1 Like