Error in for loop

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].
5 Likes