A question about code

A=Any[]
for i=1:3
    A[i]=2
    #print(A)
end

what is the matter about the code?thank you!

As it is written in error, your array A is empty, you can easily check it with

length(A) # 0

As such you can’t assign value to an element which is outside of the bounds of the array.

You can do one of the following:

  1. Preallocate array if you know it’s length beforehand
A = Vector{Any}(undef, 3)
 for i=1:3
    A[i]=2
    #print(A)
end

2.If you do not know size of the array beforehand, you can add new elements (and effectively change it size) with the function push!

A = []
for i in 1:3
  push!(A, 2)
end

More details can be found here: Multi-dimensional Arrays · The Julia Language and here: Arrays · The Julia Language

3 Likes

I’d like to add that, if possible, try and make the array concretely typed. E.g.,

A = Vector{Float64}(undef, 3)
A = Vector{Int}(undef, 3)
A = Float64[]
A = Int[]

This matters for performance, not correctness, so it’s less important, but nice to keep in mind.

2 Likes

thank you !

it works,thank you!