Search code examples
data-structuresjulia

How to index into second level of data structure


I'm new to julia, and have run across this problem a few times. I often want to do something like data[:][n] to get the nth index of every item of data. Sometimes I can find a hacky way around it, like [vv...;;][3,:] for a vector of vectors, or [plt.series_list[i][:label] = newlabels[i] for i in eachindex(newlabels)], but sometimes I just give up and restructure the data I'm working with.
Is there an easier way to interact with slices of the data underneath the top layer?


Solution

  • If the array is a vector of vectors, there is broadcasting getindex:

    julia> a = [[1,2,3], [10,20,30], [100,200,300]]
    3-element Vector{Vector{Int64}}:
    [1, 2, 3]
    [10, 20, 30]
    [100, 200, 300]
    
    julia> getindex.(a, 3)
    3-element Vector{Int64}:
       3
      30
     300
    
    If the array is a 2D array (a Matrix), you can index with the `:` wildcard:
    
    julia> b = [1 2 3; 10 20 30; 100 200 300]
    3×3 Matrix{Int64}:
       1    2    3
      10   20   30
     100  200  300
    
    julia> b[:, 3]
    3-element Vector{Int64}:
       3
      30
     300