Get the Nth element of all vectors inside an array of vectors

I have a vector of vectors like:

a = [[1,2,3],[4,5,6],[7,8,9]]

When I want the first element of the first vector inside the vector, I simply use:

a[1][1]

But when I try to get the first element of all the vector using

a[:][1]

I get all the elements of the first vector

1
2
3

instead of the of

1
4
7

Is there any way to get the correct elements using something like the simplified notation above or using broadcasting, instead of using a for loop?

getindex.(a,1) should do what you want here. Unfortunately I don’t think there is a way to do this with []

8 Likes
julia> a[1, :]
3-element Array{Int64,1}:
 1
 4
 7

julia> a[:, 1]
3-element Array{Int64,1}:
 1
 2
 3

Note that a[1][:] does not work. It first does a[1] which is the number 1. Later, it tries to access all numbers [:] of that single number, which results in an error.

2 Likes

getindex.(a,1) works, but I’ll throw out some worthy mentions to share some of the fun of Julia.

first.(a)

or
map(x -> x[1],a)

or

[ v[1] for v in a ]

also work but may have performance penalties.

4 Likes

Hi Roble,

That solution works when a is a 2D (3x3) array, which is a little bit different from what I asked. But, yes, I can convert my vector of vectors in an 2D array and that will work.

Thanks!

1 Like

Exactly what I was looking for! Thanks!

1 Like