arraysjulia

# Pushing to array in Julia: failure to create inner arrays of varying dimension

I have a loop like so:

``````edge_weights = Int[];
edge_weights_array = [edge_weights for _ in 1:199];

#make a little function for figuring out column indices
function get_columnindices(graph_base_table)::Tuple{Int,Int}
ncol(graph_base_table)
return (19,ncol(graph_base_table))
end
pairings_array = [pairings for _ in 1:grouped_by_year.ngroups];
graph_array = [SimpleWeightedGraph(get_columnindices(group)[2]-get_columnindices(group)[1]+1) for group in graph_base_table_array];
graphs = zip(graph_array,edge_weights_array,graph_base_table_array);
for graph in graphs
for i in 19:ncol(graph[3]), j in i+1:ncol(graph[3]) # iterate over all combinations of columns
w = dot(graph[3][!, i], graph[3][!, j])        # calculate how many times (i,j) occurs
if w > 0
push!(graph[2], w)
end
end
end
``````

I noticed that the array of arrays in the second position `push!(graph[2], w)` gets enlarged a lot more than I want. It should be an array of arrays where the inner array size varies. Somehow, they all end up the same size. From the `zip`, does `graph[2]` not access the inner array and moves on to the next inner array? Somehow, the code ends up enlarging the inner arrays all to the same size.

How can I create inner arrays in `edge_weights_array` that vary in size? Am I using `push` wrong?

Solution

• The issue is that `edge_weights_array = [edge_weights for _ in 1:199]` creates an array where every element is the same underlying array — it doesn't make 199 copies of `edge_weights`.

``````julia> edge_weights = Int[];

julia> edge_weights_array = [edge_weights for _ in 1:199];

julia> push!(edge_weights, 1)
1-element Vector{Int64}:
1

julia> edge_weights_array
199-element Vector{Vector{Int64}}:
[1]
[1]
[1]
⋮
[1]
[1]
[1]
``````

You need to create separate ones, with `edge_weights_array = [Int[] for _ in 1:199]`.