Since this situation comes up once in a while, it might be nice to have a
copyfill which does a copy on each cell. In code:
function copyfill!{T}(a::Array{T}, x)
xT = convert(T, x)
for i in eachindex(a)
@inbounds a[i] = copy(xT)
end
return a
end
copyfill(v, dims::Dims) = copyfill!(Array(typeof(v), dims), v)
copyfill(v, dims::Integer...) = copyfill!(Array(typeof(v), dims...), v)
And then we have:
julia> m = copyfill(Int[1],3,3)
3x3 Array{Array{Int64,1},2}:
[1] [1] [1]
[1] [1] [1]
[1] [1] [1]
julia> push!(m[1,1],2)
2-element Array{Int64,1}:
1
2
julia> m
3x3 Array{Array{Int64,1},2}:
[1,2] [1] [1]
[1] [1] [1]
[1] [1] [1]
As some would expect. Is there a +1 on this?
On Sunday, November 29, 2015 at 1:36:03 PM UTC+2, Kristoffer Carlsson wrote:
>
> I guess the simplest would be:
>
> [Int[] for i = 1:3, j=1:3, k=1:3]
>
>
> And to repeat what Milan already said, you don't want fill! because then
> all your arrays point to the same memory location.
>
> On Sunday, November 29, 2015 at 11:51:28 AM UTC+1, Aleksandr Mikheev wrote:
>>
>> 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!
>>
>>