[英]How to convert from Array{Float64,2} to Array{Array{Float64,1},1} in Julia
So, I have been working with a dataset (of my own creation) which was name as mydata
and it was a 10000-element Array{Array{Float64,1},1}:
.所以,我一直在使用一个名为
mydata
的数据集(我自己创建的),它是一个10000-element Array{Array{Float64,1},1}:
。 The thing is that I stored it into my computer by using writedlm("mydata",mydata)
and now, when I read it using readdlm("mydata",mydata)
, I recover a matrix of type Array{Float64,2}:
.问题是我使用
writedlm("mydata",mydata)
将其存储到我的计算机中,现在,当我使用readdlm("mydata",mydata)
读取它时,我恢复了Array{Float64,2}:
.
The question is:问题是:
10000-element Array{Array{Float64,1},1}:
, or, at least, transform my recovered matrix to a Array{Array{Float64,1},1}:
type?10000-element Array{Array{Float64,1},1}:
,或者至少将我恢复的矩阵转换为Array{Array{Float64,1},1}:
类型? Thanks!谢谢!
You can drop the dimension using [:]
operator:您可以使用
[:]
运算符删除维度:
julia> a=rand(2,3)
2×3 Array{Float64,2}:
0.896784 0.653296 0.939789
0.113942 0.178925 0.470658
julia> @view a[:]
6-element view(::Array{Float64,1}, :) with eltype Float64:
0.8967838440135203
0.1139418024781611
0.6532956345656487
0.17892503362478984
0.9397886609896129
0.4706578162765451
The advantage of the above code is that no data is copied so this is practically a zero cost.上述代码的优点是不会复制任何数据,因此这实际上是零成本。
There is also a reshape(a,6)
(or more generally, reshape(a, length(a))
) option which does not copy the data neither (you still get reference to the same memory location).还有一个
reshape(a,6)
(或更一般地说, reshape(a, length(a))
)选项,它也不会复制数据(您仍然可以引用相同的 memory 位置)。
Finally, note that you might want to use Array
slicing operator to actually be sure that you are getting only the first columns (again @view
avoids data copying):最后,请注意,您可能希望使用
Array
切片运算符来实际确保您只获得第一列(再次@view
避免数据复制):
julia> @view a[:,1]
2-element view(::Array{Float64,2}, :, 1) with eltype Float64:
0.8967838440135203
0.1139418024781611
Apart from patterns shown by Przemyslaw, I also often use:除了 Przemyslaw 展示的模式外,我还经常使用:
julia> a=rand(2,3)
2×3 Array{Float64,2}:
0.946128 0.902697 0.831427
0.647748 0.934436 0.221258
julia> vec(a)
6-element Array{Float64,1}:
0.9461283739840134
0.6477484162303082
0.9026969223072401
0.934435667665475
0.8314267308266441
0.22125755489262455
The result of vec(a)
also shares data with a
(so there is no copying) and it can be slightly faster to construct and use later than @view a[:]
as it is a plain vector rather than a view. vec(a)
的结果还与a
共享数据(因此没有复制),并且它的构造和使用比@view a[:]
稍快一些,因为它是一个普通向量而不是视图。
To get a vector of vectors, you can write要获得向量的向量,您可以编写
collect(eachcol(a))
Edit: In order to get an ordinary Array{Array{Float64,1},1}
, you can use编辑:为了得到一个普通的
Array{Array{Float64,1},1}
,你可以使用
collect.(eachcol(a))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.