有效地构造具有由函数返回的2元素数组{Float64,1}的数组

时间:2018-03-02 11:15:14

标签: arrays julia

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

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循环构建它,但是正在寻找一种更有效的方法。

谢谢!

2 个答案:

答案 0 :(得分:2)

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本身几乎没有开销,'使用笛卡尔索引很快。

答案 1 :(得分:0)

沿着这些方向的东西

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
相关问题