Error in for loop

Hello all,

I am writing a simple code given as:

for i in 1:4
    b[i] = sum(M[i,j]*z[j] for j in items)+sum(N[i,j]*w[j] for j in items)+q[i]

it is giving me error

BoundsError: attempt to access 0-element Vector{Any} at index [1]

Can anyone tell me whats going on.


One or the arrays you are trying to access is empty. Julia won’t automatically resize an array for you like MATLAB, you need to preallocate the memory first, or just make sure that you are accessing the memory within the bounds.

1 Like

still no idea whats going on :frowning: b[i] is just a new vector that i am assigning to the values of right hand side. very simple code. the right hand side is working, when i try to assign the value it gives me error

@show b

yes its print b four times but i want to save them in a vector, cant i just save it like b[i]?

Unlike Matlab, Julia does not automatically grow arrays when you assign to them. The following code:

b = [] # initialize to empty array
b[1] = 7
b[2] = 3

is perfectly valid in Matlab but will give an error in Julia. (Most languages will give you an error for something like this; Julia Matlab is the odd one out.)

You have at least three options:

  1. Pre-allocate the array of the desired size and type, e.g. b = Vector{Float64}(undef, 4) to pre-allocate an array of 4 floats (with undefined/arbitrary values) that you can write into, or b = zeros(4) for an array of zeros.
  2. For Matlab-like behavior of appending one element at a time, use push!(b, someval) to append someval to the end of b, increasing the length of b. (This is done efficiently under the hood, with minimal copying of data.)
  3. Use map, broadcasting, or a comprehension to create the array while assigning its elements to a particular computation, e.g. b = [sum(...)+q[i] for i in 1:4].

Thank you so much, make sense now.

I think you meant that Matlab is the odd one. I believe Lua also allows this, if I remember correctly.

Yes, sorry.