Extract vector of values from vector of T


Imagine I have

type T


I would then like to write something like


this doesn’t work because “type Array has no field x”. I can certainly extract all the x[1] from the individual members of the array v and put them in a vector x1 with a loop but I was wondering if there is a more Julia-esque way of doing it.


Note that this doesn’t create any T objects (elements of v are #undef). You probably want

v = [T() for _ = 1 : 10]

Then to get the x1s you can do e.g.

map(t -> t.x[1], v)


(t -> t.x[1]).(v)


Interestingly, this is a good example of why the Array constructors have been changed in 0.7. In 0.7, to declare v the way you did you’d have to explicitly do

v = Array{T}(undef, 10)


v = Array{T}(undef, 10)

Fixed that for you :slight_smile:


Oh god, did this seriously just get changed? I had done so much inserting of uninitialized… When did this happen?


Search and replacing `uninitialized´ should be fairly easy though.
Took me only a few minutes for whole of Base.


Well, not sure I would have voted for undef but uninitialized is definitely one of the hardest words to type in the English language, so I’m not complaining.


Yes, I knew that my elements of v are #undef, just wanted to keep the description to a minimum. The interesting part for me was the

map(t -> t.x[1], v)

Thanks! (for all the help I am receiving here I owe you all beer/coffee/whatever… ring a bell if you ever come to Padua/Venice, Italy)


By the way, all of the suggestions here are good ones, but it’s worth noting that they’re all just helpful shortcuts for extracting each x element in a loop. One of the nicest things about Julia is that your first instinct (“extract all the x[1] from the individual members of the array v and put them in a vector x1 with a loop”) is basically the right thing to do and will be just as efficient as the “built-in” solutions like map. The map function is just nice because it creates that loop for you and makes the intent of your code clear.


This is a lengthy thread, but you might find the discussion interesting