Le dimanche 29 novembre 2015 à 02:51 -0800, Aleksandr Mikheev a écrit :
> Hi all. Once again I have some questions about Julia.
> 
> I know that there is a possibility to create a list of arrays. For
> exmple:
> 
> s = fill(Array(Int64,1),4)
> 
> And then I can do something like this:
> 
> s[1] = [1; 2]
> s[1] = [s[1]; 5]
> 
> By parity of reasoning I did this:
> 
> s = fill(Array(Int64,1),4,4,4)
> 
> And it worked fine. But in both cases I had initial elements in s
> (like when I construct arrays with Array{Int64}(m,n)):
> 
> julia> s = fill(Array(Int64,1),3,3,3)
> 3x3x3 Array{Array{Int64,1},3}:
> [:, :, 1] =
>  [2221816832]  [2221816832]  [2221816832]
>  [2221816832]  [2221816832]  [2221816832]
>  [2221816832]  [2221816832]  [2221816832]
> 
> 
> [:, :, 2] =
>  [2221816832]  [2221816832]  [2221816832]
>  [2221816832]  [2221816832]  [2221816832]
>  [2221816832]  [2221816832]  [2221816832]
> 
> 
> [:, :, 3] =
>  [2221816832]  [2221816832]  [2221816832]
>  [2221816832]  [2221816832]  [2221816832]
>  [2221816832]  [2221816832]  [2221816832]
> 
> 
> Is there something I could do to prevent this? I know I could easily
> fix it by:
> 
> 
> for i = 1:3
> for j = 1:3
> for k = 1:3
> s[i,j,k] = []
> end
> end
> end
> 
> But I guess this is a weird solution.
> 
> Thank you in advance!
I'm not sure exactly what kind of list of arrays you're trying to
create. If you want an array of empty arrays, the best solution is the
for loops you show above, or a shorter comprehension form:
[[] for i in 1:3, j in 1:3, k=1:3]

On the contrary, be careful with fill() as it doesn't make a copy of
its first argument. That is, it will create an array in which all
elements hold a reference to a single common object. So check that,
call e.g.:
s[1,1][1] = 0
and see how all the elements in the array are affected.


Finally, if your goal is to fill the array later with arrays, you can
simply create an empty array of arrays:
x = Array{Array{Int,1}}(4, 4, 4)

and fill it manually later:
x[1,1] = [1]

as long as you don't try to access undefined elements.


Regards

Reply via email to