我需要在Julia中创建预定义结构的Vector of Vector。到目前为止,我正试图通过迭代级联来完成这个任务:
struct Scenario
prob::Float64 # probability
time::Float64 # duration of visit
profit::Int64 # profit of visit
end
possible_times = [60, 90, 120, 150, 180]
scenarios = Scenario[]
for point in 1:num_points
profit = rand(1:4)
new_scenario = [Scenario(0.2, possible_times[i], profit) for i=1:5]
scenarios = vcat(scenarios, new_scenario)
end
display(scenarios)但我有以下几点
Warning: Assignment to `scenarios` in soft scope is ambiguous because a global variable by the same name exists: `scenarios` will be treated as a new local. Disambiguate by using `local scenarios` to suppress this warning or `global scenarios` to assign to the existing global variable.
ERROR: LoadError: UndefVarError: scenarios not defined那么第一个问题是如何保存中间连接的结果?第二个问题是用这种方式实现目标正确吗?或者我做错了还有别的办法?
发布于 2022-03-14 12:44:22
通常使用append!而不是vcat
for point in 1:num_points
profit = rand(1:4)
new_scenario = [Scenario(0.2, possible_times[i], profit) for i=1:5]
append!(scenarios, new_scenario)
end如果要使用vcat,请使用global关键字:
for point in 1:num_points
profit = rand(1:4)
new_scenario = [Scenario(0.2, possible_times[i], profit) for i=1:5]
global scenarios = vcat(scenarios, new_scenario)
end关键是在scenarios = vcat(scenarios, new_scenario)中重新分配scenarios变量,该变量位于全局范围内。
一般来说,情况要复杂一些(Julia行为将取决于代码是在交互式会话中运行还是在非交互式会话中运行),正如您可以在“朱莉娅手册”的本节 (软作用域部分的第3项)中看到的那样。但是,如果您不想深入研究范围的细节,一条简单而安全的规则是:如果为全局变量赋值,那么使用global作为赋值操作的前缀。
https://stackoverflow.com/questions/71466436
复制相似问题