在 Julia 中创建长度为 n 的向量

Geo*_*ery 5 julia

我想创建一个长度的向量/数组,n然后再填充。

我怎样才能做到这一点?它是否必须已经填充了一些东西?

小智 8

例如,如果你想要一个长度为 10 的整数向量,你可以写

v = Vector{Int}(undef, 10)
Run Code Online (Sandbox Code Playgroud)

对于维度 (2, 3, 4) 的整数数组更通用

a = Array{Int}(undef, (2, 3, 4))
Run Code Online (Sandbox Code Playgroud)

请注意,这会用垃圾值填充 Vector/Array,因此这可能有点危险。作为替代方案,您可以使用

v = Vector{Int}()
sizehint!(v, 10)
push!(v, 1) # add a one to the end of the Vector
append!(v, (2, 3, 4, 5, 6, 7, 8, 9, 10)) # add values 2 to 9 to the end of the vector
Run Code Online (Sandbox Code Playgroud)

sizehint! 不是必需的,但它可以提高性能,因为它告诉 Julia 期望 10 个值。

还有其他函数,例如zeros, onesorfill可以提供已填充数据的向量/数组。