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?
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.
"Appending" adds to the end of a list, "pushing" adds to the front.
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.
Your code has two problems:
n_minus_1
array at index 1
while this array is still empty (has 0
length) - this throws you an error;.
(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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With