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:
- 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, orb = zeros(4)for an array of zeros. - For Matlab-like behavior of appending one element at a time, use
push!(b, someval)to appendsomevalto the end ofb, increasing the length ofb. (This is done efficiently under the hood, with minimal copying of data.) - 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].