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

标签 arrays for-loop julia bounds arrayaccess

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

注意事项:

  1. 对于这种类型的代码,还可以查看Parameters.jl 包——它对代理构造函数来说非常方便
  2. 注意构造函数是如何矢量化的
  3. Julia 中的类型以大写字母开头(因此 Person)
  4. 我假设对于 child ,您想尝试每一对 parent ,因此这就是构建循环的方法。您不需要评估同一对 parent 作为 (i,j) 然后再作为 (j,i)。
  5. eachindex 应该用在 Array 上 - 在标量上没有意义

关于arrays - 用于访问一维数组的 Julia For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62374988/

相关文章:

php - 如何在 Laravel 中合并一个数组元素?

arrays - 根据函数删除 Julia 矩阵的行

julia - 类似 Matlab 的 Julia 调试工具

python - 检索一行 2 for 循环内最里面的值?

python - 在 python reportlab 中循环遍历一个表

java - 对于每个循环不返回值?

julia - 我可以像操作字符串一样操作符号吗?

javascript - 使用 Set 在对象数组中查找唯一元素不起作用

javascript - 从数组中随机选择然后将选择分配给变量

java - 打印数组 : memory address or its content?