【问题标题】:Efficiently construct array with 2-element Array{Float64,1} returned by a function使用函数返回的 2 元素 Array{Float64,1} 有效地​​构造数组
【发布时间】:2018-03-02 11:15:14
【问题描述】:

我有一个函数,它返回一个二维数组:

2-element Array{Float64,1}:
 0.809919
 2.00754

我现在想有效地对其进行采样并将所有结果存储在一个包含 2 行和 n 列的数组中。问题是我得到了一个向量向量。我怎样才能将它展平或构建它?

一个玩具示例如下:

julia> [rand(2) for i=1:3]
3-element Array{Array{Float64,1},1}:
 [0.906644, 0.614673]
 [0.426492, 0.67645]
 [0.473704, 0.726284]

julia> [rand(2)' for i=1:3]
3-element Array{RowVector{Float64,Array{Float64,1}},1}:
 [0.403384 0.431918]
 [0.410625 0.546614]
 [0.224933 0.118778]

我希望得到这样的结果:

julia> [rand(2) rand(2) rand(2)]
2×3 Array{Float64,2}:
 0.360833  0.205969  0.209643
 0.507417  0.317295  0.588516

其实我的梦想是:

julia> [rand(2) rand(2) rand(2)]'
3×2 Array{Float64,2}:
 0.0320955  0.821869
 0.358808   0.26685
 0.230355   0.31273

有什么想法吗?我知道我可以通过 for 循环构造它,但正在寻找更有效的方法。

谢谢!

【问题讨论】:

    标签: arrays julia


    【解决方案1】:

    RecursiveArrayTools.jl 有一个 VectorOfArray 类型,它以您想要的方式调度:

    julia> using RecursiveArrayTools
    
    julia> A = [rand(2) for i=1:3]
    3-element Array{Array{Float64,1},1}:
     [0.957228, 0.104218]
     [0.293985, 0.83882]
     [0.788157, 0.454772]
    
    julia> VectorOfArray(A)'
    3×2 Array{Float64,2}:
     0.957228  0.104218
     0.293985  0.83882
     0.788157  0.454772
    

    关于时机:

    julia> @benchmark VectorOfArray(A)'
    BenchmarkTools.Trial:
      memory estimate:  144 bytes
      allocs estimate:  2
      --------------
      minimum time:     100.658 ns (0.00% GC)
      median time:      111.740 ns (0.00% GC)
      mean time:        127.159 ns (3.29% GC)
      maximum time:     1.360 μs (82.71% GC)
      --------------
      samples:          10000
      evals/sample:     951
    

    VectorOfArray 本身几乎没有开销,而' 使用笛卡尔索引速度很快。

    【讨论】:

    • 很棒的包装!感谢您的提示。
    【解决方案2】:

    类似的东西

    using BenchmarkTools
    
    function createSample!(vec::AbstractVector)
      vec .= randn(length(vec))
      return vec
    end
    
    function createSamples!(A::Matrix)
      for row in indices(A, 1)
        createSample!(view(A, row, :))
      end
      return A
    end
    
    A = zeros(10, 2)
    
    @benchmark createSamples!(A)
    

    可能会有所帮助。我的笔记本电脑上的时间给出了:

    Main> @benchmark createSamples!(A)
    BenchmarkTools.Trial:
      memory estimate:  1.41 KiB
      allocs estimate:  20
      --------------
      minimum time:     539.104 ns (0.00% GC)
      median time:      581.194 ns (0.00% GC)
      mean time:        694.601 ns (13.34% GC)
      maximum time:     10.324 μs (90.10% GC)
      --------------
      samples:          10000
      evals/sample:     193
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      相关资源
      最近更新 更多