Referencing Specific Positions in an Array with Functions in Julia
Overview
When multiple arrays are given, there are often situations where one wants to access a specific element of these arrays, for example, the third element in each array. In Julia, this can be implemented through broadcasting the getindex() function.
Code
getindex.()
julia> seq_ = [collect(1:k:100) for k in 1:10]
10-element Vector{Vector{Int64}}:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10 … 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19 … 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
[1, 4, 7, 10, 13, 16, 19, 22, 25, 28 … 73, 76, 79, 82, 85, 88, 91, 94, 97, 100]
[1, 5, 9, 13, 17, 21, 25, 29, 33, 37 … 61, 65, 69, 73, 77, 81, 85, 89, 93, 97]
[1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96]
[1, 7, 13, 19, 25, 31, 37, 43, 49, 55, 61, 67, 73, 79, 85, 91, 97]
[1, 8, 15, 22, 29, 36, 43, 50, 57, 64, 71, 78, 85, 92, 99]
[1, 9, 17, 25, 33, 41, 49, 57, 65, 73, 81, 89, 97]
[1, 10, 19, 28, 37, 46, 55, 64, 73, 82, 91, 100]
[1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
julia> getindex.(seq_, 3)
10-element Vector{Int64}:
3
5
7
9
11
13
15
17
19
21
first(), last()
first() is the same as getindex(, 1), but last() is special because there is no equivalent expression like getindex(, end). It’s often necessary to get the last result as the program iterates, and the index of that last element can vary greatly, so it’s good to know the last() function.
julia> first.(seq_)
10-element Vector{Int64}:
1
1
1
1
1
1
1
1
1
1
julia> last.(seq_)
10-element Vector{Int64}:
100
99
100
97
96
97
99
97
100
91
Environment
- OS: Windows
- julia: v1.9.0
