Julia For循环用于访问一维数组

问题描述 投票:1回答:1

我正在尝试运行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
arrays for-loop julia bounds arrayaccess
1个回答
0
投票

我很少猜测,但是也许这是您想要的代码:

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应在Array s上使用-在标量上没有意义
© www.soinside.com 2019 - 2024. All rights reserved.