I want to run a code from a paper by Julia. There is a function about data storage. The function need to insert a function called oracle. I create a c vector and put it into its code but there comes an error. Here is my code :
function portfolio(c::Vector{Float64})
d = length(c)
mod = Model(with_optimizer(Gurobi.Optimizer, OutputFlag = 0))
@variable(mod, 0<= w[1:d] <= 1)
@constraint(mod, sum(w[i] for i = 1:d) <= 400)
@objective(mod, Min, dot(c, w))
optimize!(mod)
z_ast = objective_value(mod)
w_ast = value.(w)
return (z_ast, w_ast);
end
c_df = vec(df[2])
X_df = df[1]
function oracle_dataset(c,oracle)
(d, n) = size(c)
z_star_data = zeros(n)
w_star_data = zeros(d, n)
for i = 1:n
(z_i, w_i) = oracle(c[:,i])
z_star_data[i] = z_i
w_star_data[:,i] = w_i
end
return (z_star_data, w_star_data)
end
oracle_dataset(c_df, portfolio)
The error is:
BoundsError: attempt to access Tuple{Int64} at index [2]
Stacktrace:
[1] indexed_iterate
@ .\tuple.jl:86 [inlined]
[2] oracle_dataset(c::Vector{Float64}, oracle::typeof(portfolio))
@ Main .\In[15]:63
[3] top-level scope
@ In[15]:73
[4] eval
@ .\boot.jl:360 [inlined]
[5] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
@ Base .\loading.jl:1116
Why does this happen? I have tried another easier example and there is no error in putting a function inside a function. My easier code is :
function foo(x)
g = x*3
return g;
end
function bar(c,func)
result = func(c)
return result;
end
num = 3
bar(num,foo)
Thank you for your help...I really want to know what mistake i had done in here. Thank you~
CodePudding user response:
It looks like you try to access second element in tuple, while there is only one element, probably here:
c_df = vec(df[2])
CodePudding user response:
The c_df
which you pass to oracle_dataset
is actually a Vector (which you can see in the 6th line of the stacktrace, starting with [2]
), which is one-dimensional. This means that size(c)
in the first line of the oracle_dataset
function will return a 1-tuple. However, the author of that function seems to be assuming that c
will be a Matrix, which is 2-dimensional. Calling size
on that would return a 2-tuple, which is deconstructed to (d, n)
in the function.
The error seems to specifically trigger on the line :
(d, n) = size(c)
meaning that you would likely need to supply a Matrix
as c
.
I can't speak to what that matrix would look like or how you would construct it. Perhaps df[2]
is a matrix itself?