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 ?
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
k = Int[ ] in this example.Array{Int64}(undef, n) as described in the docs, to make an array of set dimensions (1 dimension, size n) and type (Int64), with uninitialized values.See: https://en.wikibooks.org/wiki/Introducing_Julia/Arrays_and_tuples#Uninitialized
"Using comprehensions and generators to create arrays"
k = [i for i in 1:10]
How do you know it's not working? Try evaluating k:
n= 10
for i in 1:n
k[i]= i
end
k
10-element Array{Int64,1}: 1 2 3 4 5 6 7 8 9 10
A more succinct way of doing the same thing:
collect(1:10)
k was in fact defined in another cell.
k = -5:5. Then you can dok[3]and get2back, which is the third element of the range.