# BoundsError: attempt to access 0-element Array{Any,1} at index 

Hello, this is my code:

``````distvec = []
for indm = 1:M
global distvec
distvec[indm] = -(-Nvec* px[indm]- Nvec* py[indm]- Nvec* pz[indm])/sqrt(Nvec^2+Nvec^2+Nvec^2)
end
``````

The error I get:

``````BoundsError: attempt to access 0-element Array{Any,1} at index 
``````

How do I solve this issue?

Thank you!

You want to preallocate `distvec` to the correct length, e.g. if your numbers are floats do

``````distvec = zeros(M)
``````

or `Array{Float64, 1}(undef, M)` if you want to leave the elements uninitialized.

3 Likes

The line `distvec = []` declares an empty array, so you cannot do `distvec = 0.1`. You could do `push!(distvec, 0.1)`, but it’s better to pre-allocate the array with the correct size.

Also, avoid globals as much as possible. If you put this code in a function you don’t need a global:

``````function f(M, Nvec, px, py, pz)
# Preallocate an array full of 0.0 (write e.g. zeros(Int, M) to choose a type different from Float64)
distvec = zeros(M)
for indm = 1:M
distvec[indm] = -(-Nvec* px[indm]- Nvec* py[indm]- Nvec* pz[indm])/sqrt(Nvec^2+Nvec^2+Nvec^2)
end
return distvec
end

f(5, [1,2,3], 1:5, 1:5, 1:5)
``````

If you don’t want to preallocate, at least create an array with a specific type, e.g. `distvec = Float64[]` instead of `distvec = []`.

You can also use array comprehension:

``````M = 5
Nvec = [1,2,3]
px = py = pz = 1:M

distvec = [-(-Nvec*px[indm] - Nvec*py[indm] - Nvec*pz[indm]) / norm(Nvec)
for indm in 1:M]
``````
3 Likes

Thank you all!