4

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 ?

1
  • You often don't actually need an array (that occupies memory) and can use a range instead, e.g. k = -5:5. Then you can do k[3] and get 2 back, which is the third element of the range. Commented Jul 8, 2016 at 17:44

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

I like the second method even when I do know the size. However, you should define the array initially with the correct argument type, e.g. k = Int[ ] in this example.
It seems the first version you give doesn't work in Julia 1.6+ (maybe earlier versions too; gives a MethodError). Instead, one can use the 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.
5

The simplest way to get the specific array you want is this:

k = collect(1:10)

If you want to define an array in a loop, then you first need to preallocate the array, e.g. using k = zeros(10) and then specify the values:

n = 10
k = zeros(n)
for i = 1:n
    k[i] = i
end

Comments

3

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]

Comments

-3

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)

2 Comments

In 0.4.6 this snippet will throw an UndefVarError, and I suspect that in other versions too. The basic asumption is that the array isn't initialized in the question, and the author is just testing Matlab behaivour, where this works.
Thanks for the explanation. Embarrassing mistake. I ran the code in a Jupyter notebook -- where k was in fact defined in another cell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.