matrix - 在 Julia 中将元组向量转换为矩阵
问题描述
假设我们有一个函数,它给了我们以下内容:
julia> ExampleFunction(Number1, Number2)
5-element Vector{Tuple{Int64, Int64}}:
(2, 2)
(2, 3)
(3, 3)
(3, 2)
(4, 2)
我想转换Vector{Tuple{Int64, Int64}}
成一个矩阵,或者在我的情况下我想把它转换成一个 5x2 矩阵。
解决方案
最快的代码将是非复制代码。在另一篇文章的示例中,这会将时间从毫秒减少到纳秒:
julia> xs
1000000-element Vector{Tuple{Int64, Int64}}:
(5, 1)
(4, 3)
⋮
(1, 4)
(9, 2)
julia> @btime reshape(reinterpret(Int, $xs), (2,:))'
10.611 ns (0 allocations: 0 bytes)
1000000×2 adjoint(reshape(reinterpret(Int64, ::Vector{Tuple{Int64, Int64}}), 2, 1000000)) with eltype Int64:
5 1
4 3
⋮
1 4
9 2
对于复制代码,最快的将是:
function convert_to_tuple4(x)
out = Matrix{eltype(x[1])}(undef, length(x), length(x[1]))
for i ∈ 1:length(x)
@inbounds @simd for j ∈ 1:length(x[1])
out[i, j] = x[i][j]
end
end
out
end
基准:
julia> @btime convert_to_tuple3($xs);
3.488 ms (2 allocations: 15.26 MiB)
julia> @btime convert_to_tuple4($xs);
2.932 ms (2 allocations: 15.26 MiB)
推荐阅读
- android - 错误:找不到 com.google.gms:google-services:4.2.0
- flutter - How to test Flutter widgets on different screen sizes?
- excel - 动态标签颜色问题
- asp.net - Linq to sql Query 在 Asp.net mvc Web 应用程序中运行非常缓慢
- c# - 测试 TextBox 是否存在 C# WPF
- xamarin.forms - 对类型“Assembly”的引用声称它在“System.Runtime”中定义,但在 Xamarin UWP 中找不到
- python - 如何存储/缓存类中方法的值,以便以后在同一类的其他方法中使用?
- angular - Angular 7窗口调整大小事件未在服务中运行
- regex - Countif url 匹配正则表达式
- html - 在边框上放置边距 - css