Julia select element from tuple for each row in array
Asked Answered
R

2

5

I know there has to be a clever way to do this in Julia but I'm stumped. I have a 1d array of tuples and I want to extract the third element from each row of the array. Here is an example of what I'm working with:

julia> experArr 20-element Array{(Any,Any,Any),1}:
 (4000,0.97613,1.6e6) 
 (2000,0.97613,800000.0)
 (8000,0.97613,3.2e6) 
 (1000,0.97613,400000.0)
 ...

My first thought was to do something like this:

julia> experArr[:][3]

but that returns the following:

julia> experArr[:][3] 
(8000,0.97613,3.2e6)

What I want it to return is this:

20-element Array{Any,1}:
1.6e6
800000.0
3.2e6
400000.0
...

I have tried several other permutations of indexing but I keep only returning a single element. I feel that there is a right way to do this and I'm just missing

Rickierickman answered 12/3, 2014 at 4:52 Comment(0)
C
4

experArray[:] is just a copy of your original array, so that's effectively a no-op. The easiest way to do this is with a comprehension:

[ x[3] for x in experArr ]

You could also do it with map:

map(x->x[3], experArr)

For the time being, the comprehension version is likely to be faster and have better type behavior.

Coincide answered 12/3, 2014 at 5:17 Comment(1)
Thank you. I just stumbled across the 'map' method but the comprehension way looks more Julia-eque.Rickierickman
S
7

Essentially the same as Stefan's answer, but a little more concise, you could broadcast getfield over your array:

getfield.(experArr, 3)
Schild answered 27/11, 2019 at 4:32 Comment(0)
C
4

experArray[:] is just a copy of your original array, so that's effectively a no-op. The easiest way to do this is with a comprehension:

[ x[3] for x in experArr ]

You could also do it with map:

map(x->x[3], experArr)

For the time being, the comprehension version is likely to be faster and have better type behavior.

Coincide answered 12/3, 2014 at 5:17 Comment(1)
Thank you. I just stumbled across the 'map' method but the comprehension way looks more Julia-eque.Rickierickman

© 2022 - 2024 — McMap. All rights reserved.