Reputation: 2014
I have defined a compound type like
type Position
Date::DateTime
x::AbstractFloat
y::AbstractFloat
z::AbstractFloat
end
and a array 1-dimensional Array of object (compound type) is defined like this
arr = [Position(DateTime(2016,1,1,10,00,00),0,0,0),
Position(DateTime(2016,1,1,10,00,01),2,0,0),
Position(DateTime(2016,1,1,10,00,02),2,1,0),
Position(DateTime(2016,1,1,10,00,03),2,2,0),
]
I can easily get a_Dates
(array of dates) using
a_Dates = map(rec->rec.Date, arr)
but I don't know how I can get a 2-dimensional Array of positions (x, y, z)
Ideally I would like a solution without for loop. For this I know I can do (for example)
Nrows, Ncols = length(arr), length(fieldnames(Position)) - 1
data = zeros(Nrows, Ncols)
for i in 1:Nrows
for j in 1:Ncols
data[i, j] = getfield(arr[i], j + 1)
end
end
Upvotes: 2
Views: 103
Reputation: 11
Is [getfield(p, f) for p in arr, f in (:x, :y, :z)]
what you are looking for?
(In julia 0.4, this will give an Array{Any}
though, but in this case you could just prefix Float64
to get the correct type.)
Upvotes: 1
Reputation: 3940
Array
new_array = map(rec->[rec.x, rec.y, rec.z], arr)
additionally
new_array = vcat(new_array)
new_array = reshape(new_array,convert(Int64, length(new_array)/3),3)
or
new_array = reshape(new_array,length(arr),3)
Upvotes: 1