3

我正在尝试运行 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
4

1 回答 1

3

我做了一些猜测,但也许这是你想要的代码:

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

笔记:

  1. 对于这种类型的代码也可以看一下Parameters.jl包——对于代理构造函数来说非常方便
  2. 注意构造函数是如何被向量化的
  3. Julia 中的类型以大写字母开头(因此Person
  4. 我假设对于孩子,您想尝试每对父母,因此这就是构建循环的方法。您不需要像 (i,j) 和 (j,i) 一样评估同一对父母。
  5. eachindex应该在Arrays 上使用 - 对标量没有意义
于 2020-06-14T22:33:04.533 回答