Bounds Error?

I am trying to run the following code:

u_vect = rand(5,2)   
for i in eachindex(u_vect)
    println(i)
    a = u_vect[i,2] 
end

And get the error: “BoundsError: attempt to access 5×2 Matrix{Float64} at index [6, 2].” Why does my 5x2 vector have 6 index positions? I know that arrays are considered one dimensional, but that still doesn’t explain the error?

eachindex goes over every index of the matrix, since your matrix has 10 entries in total, it goes from 1 to 10:

julia> eachindex(u_vect)
Base.OneTo(10)

If you only want to iterate over the first dimension of the matrix, you’ll need to use the axes function, with the desired dimension:

julia> axes(u_vect,1)
Base.OneTo(5)

julia> axes(u_vect,2)
Base.OneTo(2)
2 Likes

eachindex(u_vect) gives you the linear indices of every element in the matrix:

julia> eachindex(u_vect)
Base.OneTo(10)

So by doing u_vect[i, 2], you’re trying to access u_vect[1, 2], u_vect[2, 2], ..., u_vect[10, 2], which doesn’t work (it errors as soon as you get to u_vect[6, 2]).

If you’re using eachindex, then you want to index with just i, as in:

for i in eachindex(u_vect)
  a = u_vect[i]
  ...
end

or if you just want to iterate over the indices in the first dimension, then you want axes:

for i in axes(u_vect, 1)
  a = u_vect[i, 2]
  ...
end
4 Likes

thank you so much!

thank you!!!