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
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:
Parameters.jl
package - it is very convenient for agent constructorsPerson
)eachindex
should be used on Array
s - does not make sense on scalars