我正在尝试运行 2 个 for 循环来访问数组中的 2 个元素,(例如)
x = 100
for i in eachindex(x-1)
for j in 2:x
doSomething = Array[i] + Array[j]
end
end
而且我经常(不总是)遇到此错误或类似错误:
LoadError: BoundsError: attempt to access 36-element Array{Any,1} at index [64]
我知道有正确的方法来运行这些循环以避免边界错误,因此我使用 eachindex(x-1) == 1:x
,我将如何为 执行此操作2:x
?
我对 Julia 比较陌生,如果这不是边界错误的原因,那会是什么? - 谢谢
编辑:我正在尝试运行的缩短版本(也是,向量数组)
all_people = Vector{type_person}() # 1D Vector of type person
size = length(all_people)
... fill vector array to create an initial population of people ...
# Now add to the array using existing parent objects
for i in 1:size-1
for j in 2:size
if all_people[i].age >= all_people[j].age # oldest parent object forms child variable
child = type_person(all_people[i])
else
child = type_person(all_people[j])
end
push!(all_people, child) # add to the group of people
end
end
最佳答案
我做了一些猜测,但也许这就是您想要的代码:
struct Person
parent::Union{Nothing,Person}
age::Int
end
Person(parent::Person) = Person(parent,0)
N = 100
population = Person.(nothing, rand(20:50,N))
for i in 1:(N-1)
for j in (i+1):N
parent = population[population[i].age >= population[j].age ? i : j]
push!(population, Person(parent))
end
end
注意事项:
- 对于这种类型的代码,还可以查看
Parameters.jl
包——它对代理构造函数来说非常方便 - 注意构造函数是如何矢量化的
- Julia 中的类型以大写字母开头(因此
Person
) - 我假设对于 child ,您想尝试每一对 parent ,因此这就是构建循环的方法。您不需要评估同一对 parent 作为 (i,j) 然后再作为 (j,i)。
eachindex
应该用在Array
上 - 在标量上没有意义
关于arrays - 用于访问一维数组的 Julia For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62374988/