How to define global variables to be shared later in Julia

非 Y 不嫁゛ 提交于 2020-01-22 02:30:07

问题


I have a module in file global.jl which defines a global multidimensional array named "data":

module Global

    export data

    # GLOBAL DATA ARRAY
    data = zeros(Int32, 20, 12, 31, 24, 60, 5);

end

I have a main.jl which uses this global variable:

include("global.jl")
using .Global

println(data[14,1,15,18,0,1])

And I get the following error:

$ time /usr/local/julia-1.2.0/bin/julia main.jl
ERROR: LoadError: BoundsError: attempt to access 20Ã12Ã31Ã24Ã60Ã5 Array{Int32,6} at index [14, 1, 15, 18, 0, 1]
Stacktrace:
 [1] getindex(::Array{Int32,6}, ::Int64, ::Int64, ::Int64, ::Int64, ::Vararg{Int64,N} where N) at ./array.jl:729
 [2] top-level scope at /usr/home/user/test1/main.jl:4
 [3] include at ./boot.jl:328 [inlined]
 [4] include_relative(::Module, ::String) at ./loading.jl:1094
 [5] include(::Module, ::String) at ./Base.jl:31
 [6] exec_options(::Base.JLOptions) at ./client.jl:295
 [7] _start() at ./client.jl:464
in expression starting at /usr/home/user/test1/main.jl:4

I guess I am missing how to share global variables in a separate file in Julia. Any help is welcomed.


回答1:


The global is fine--you have a zero index, and Julia array indexes start with 1, not zero, by default:

module Global

    export data

    # GLOBAL DATA ARRAY
    data = zeros(Int32, 20, 12, 31, 24, 60, 5);

end

using .Global

function printplus42()
    println((data .+ 42)[1, 1, 1, 1, 1, :])
end

printplus42()


println(data[14,1,15,18,0,1])

yields:

[42, 42, 42, 42, 42]
ERROR:[...]attempt to access 20×12×31×24×60×5 Array{Int32,6} at index [14, 1, 15, 18, 0, 1]


来源:https://stackoverflow.com/questions/57931589/how-to-define-global-variables-to-be-shared-later-in-julia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!