Question

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

Was it helpful?

Solution 2

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.

OTHER TIPS

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

getfield.(experArr, 3)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top