我定义了一个复合类型,例如
type Position
Date::DateTime
x::AbstractFloat
y::AbstractFloat
z::AbstractFloat
end
对象的一维数组(复合类型)的定义如下
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),
]
我可以使用
轻松获取a_Dates
(日期数组)
a_Dates = map(rec->rec.Date, arr)
但我不知道如何获得一个二维位置数组(x,y,z)
理想情况下,我想要一个没有 for 循环的解决方案。 为此,我知道我可以做到(例如)
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
最佳答案
数组
new_array = map(rec->[rec.x, rec.y, rec.z], arr)
另外
new_array = vcat(new_array)
new_array = reshape(new_array,convert(Int64, length(new_array)/3),3)
或
new_array = reshape(new_array,length(arr),3)
关于arrays - 将一维对象数组(复合类型)转换为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39560340/