Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia : create an arrays in for loop

Tags:

arrays

julia

l want to create an array having this structure

k[1]= 1

k[2]= 2

k[3]= 3

k[4]= 4

l tried it in this way but it's not working

n= 10

for i in 1:n
 k[i]= i
end

any suggestions ?

like image 915
vincet Avatar asked Dec 18 '22 15:12

vincet


1 Answers

You havent initialized the array, so calling k[1] or k[2] or k[n] wont return an error

You should either:

n= 10
k = Array(Int64, n) #or Float64 or Any instead of Int64
for i in 1:n
    k[i]= i
end

or you could

n= 10
k = []
for i in 1:n
    push!(k,i)
end

I suggest the former, the other method would be more suited if you woulnt be able to determine the size of the array beforehand

like image 84
isebarn Avatar answered Dec 27 '22 04:12

isebarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!