Search code examples
arraysfor-loopjuliaboundsarrayaccess

Julia For-loops used for accessing 1D Arrays


I am trying to run a 2 for loops to access 2 elements within an array, (e.g.)

x = 100
for i in eachindex(x-1)
  for j in 2:x
    doSomething = Array[i] + Array[j]
  end
end

And often (not always) I get this error or similar:

LoadError: BoundsError: attempt to access 36-element Array{Any,1} at index [64]

I understand there are proper ways to run these loops to avoid bounds errors, hence my use of eachindex(x-1) == 1:x, how would I do this for 2:x?

I am relatively new to Julia, if this is not the reason for the bounds error, what could it be? - Thanks

EDIT: shortened version of what I am trying to run (Also yes, vector-arrays)

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

Solution

  • I made few guesses but perhaps this is the code you want:

    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
    

    Notes:

    1. For this types of code also have a look at the Parameters.jl package - it is very convenient for agent constructors
    2. Notice how the constructor has been vectorized
    3. Types in Julia are named starting with capital letters (and hence Person)
    4. I assume that for children you wanted to try each pair of parents hence this is how to construct the loop. You do not need to evaluate the same pair of parents as (i,j) and then later as (j,i).
    5. eachindex should be used on Arrays - does not make sense on scalars