Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Append to an array

Tags:

julia

Someone please help me understand this. I have the following code below. I am trying to append index[i]-1 to an empty array. However I am getting this error: "BoundsError: attempt to access 0-element Array{Any,1} at index [1]" :

sample_size_array = [9,5,6,9,2,6,9]
n_minus_1 = []
array_length = length(sample_size_array)
for i in 1:array_length
    n_minus_1[i].append(sample_size_array[i] -1)
end
println(n_minus_1)

If Julia does not understand array[0] then why is i starting at 0 and not at 1?

like image 814
N6DYN Avatar asked Aug 11 '18 22:08

N6DYN


People also ask

How do I append to an array in Julia?

Julia allows adding new elements in an array with the use of push! command. Elements in an array can also be added at a specific index by passing the range of index values in the splice! function.

What is the difference between push and append?

"Appending" adds to the end of a list, "pushing" adds to the front.

How do you reshape an array in Julia?

Reshaping array dimensions in Julia | Array reshape() Method The reshape() is an inbuilt function in julia which is used to return an array with the same data as the specified array, but with different specified dimension sizes.


1 Answers

Your code has two problems:

  • in the first iteration you are trying to access n_minus_1 array at index 1 while this array is still empty (has 0 length) - this throws you an error;
  • in Julia you do not invoke methods using a . (this symbol is used for different purposes - in this case it is parsed as field access and also would throw an error later)

To solve both those problems use push! function which appends an element at the end of an array. The code could look like this:

sample_size_array = [9,5,6,9,2,6,9]
n_minus_1 = []
array_length = length(sample_size_array)
for i in 1:array_length
    push!(n_minus_1, sample_size_array[i]-1)
end
println(n_minus_1)

However in this case the whole operation can be written even simpler as:

n_minus_1 = sample_size_array .- 1

and you do not need any loop (and here you see another use of . in Julia - in this case we use it to signal that we want to subtract 1 from every element of sample_size_array).

like image 184
Bogumił Kamiński Avatar answered Sep 26 '22 03:09

Bogumił Kamiński