如何在 julia 中将 Array{Array{Float64, 1}, 1} 转换为 Matrix? [英] How to convert Array{Array{Float64, 1}, 1} to Matrix in julia?

查看:35
本文介绍了如何在 julia 中将 Array{Array{Float64, 1}, 1} 转换为 Matrix?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的输入:

> [[0.8681299566762923,-0.3472589826095631], [3.2300860990307445,3.3731249077464946]]

如何将其转换为更令人愉悦的类型,例如 Matrix(知道维度)?

How can I convert it to more pleasant type like Matrix (knowing dimensions)?

推荐答案

你可以使用 splatting (...) 和 hcat 来得到你想要的:

You can use splatting (...) and hcat to get what you are after:

julia> a = Vector[[0.8681299566762923,-0.3472589826095631], [3.2300860990307445,3.3731249077464946]]
2-element Array{Array{T,1},1}:
 [0.8681299566762923,-0.3472589826095631]
 [3.2300860990307445,3.3731249077464946]

julia> hcat(a...)
2x2 Array{Float64,2}:
  0.86813   3.23009
 -0.347259  3.37312

或者,如果您希望将堆栈停止为行而不是列,您可以执行以下操作:

Or if you wanted stop stack as rows instead of columns you could do the following:

julia> vcat(map(x->x', a)...)
2x2 Array{Float64,2}:
 0.86813  -0.347259
 3.23009   3.37312

我不建议逐行构建 Matrix,因为这与 Julia 的 列主要数组布局.对于较大的矩阵,实际上将其堆叠为列并转置输出效率更高:

I don't recommend building a Matrix row by row as that is in conflict with Julia's column major array layout. For larger matrices it is actually more efficient to stack as columns and transpose the output:

julia> a2 = Vector{Float64}[rand(10) for i=1:5000];

julia> stackrows1{T}(a::Vector{Vector{T}}) = vcat(map(transpose, a)...)::Matrix{T}
stackrows1 (generic function with 2 methods)

julia> stackrows2{T}(a::Vector{Vector{T}}) = hcat(a...)'::Matrix{T}
stackrows2 (generic function with 2 methods)

julia> stackrows1(a2) == stackrows2(a2)  # run once to compile and make sure functions do the same thing
true

julia> @time for i=1:100 stackrows1(a2); end
elapsed time: 0.142792896 seconds (149 MB allocated, 7.85% gc time in 7 pauses with 0 full sweep)

julia> @time for i=1:100 stackrows2(a2); end
elapsed time: 0.05213114 seconds (88 MB allocated, 12.60% gc time in 4 pauses with 0 full sweep)

这篇关于如何在 julia 中将 Array{Array{Float64, 1}, 1} 转换为 Matrix?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆