Julia-将向量组合到矩阵中

  • 本文关键字:组合 向量 Julia- julia
  • 更新时间 :
  • 英文 :


假设我有两个向量x = [1, 2]y = [3, 4]。在Julia编程语言中,如何最好地组合它们来获得矩阵m = [1 2; 3 4]?提前感谢您的支持。

注意,在vcat(x', y')中,运算x'是伴随的,因此如果您处理的是没有定义伴随的复数或向量元素(例如字符串(,则不应使用它。因此,应该使用permutedims,但它在分配时会较慢。第三种方法是(诚然,打字更麻烦(:

julia> [reshape(x, 1, :); reshape(y, 1, :)]
2×2 Array{Int64,2}:
1  2
3  4

它和[x'; y']一样是非分配的,但不做递归伴随。

编辑:

Cameron注意事项:

julia> x = repeat(string.('a':'z'), 10^6);
julia> @btime $x';
1.199 ns (0 allocations: 0 bytes)
julia> @btime reshape($x, 1, :);
36.455 ns (2 allocations: 96 bytes)

所以reshape只进行最小限度的分配(它需要创建一个数组对象,而x'创建一个不需要分配的不可变结构(。

此外,我认为这是一个分配的设计决定。至于isbitsunion类型,实际上reshape返回一个结构,因此它不进行分配(类似于范围(:

julia> @btime reshape($x, 1, :)
12.211 ns (0 allocations: 0 bytes)
1×2 reshape(::Array{Union{Missing, Int64},1}, 1, 2) with eltype Union{Missing, Int64}:
1  missing

我知道的两种方法:

julia> x = [1,2];
julia> y = [3,4];
julia> vcat(x', y')
2×2 Array{Int64,2}:
1  2
3  4
julia> permutedims(hcat(x, y))
2×2 Array{Int64,2}:
1  2
3  4

还有一个选项-这个选项既适用于数字,也适用于其他对象作为Strings:

julia> rotl90([y x])
2×2 Array{Int64,2}:
1  2
3  4

怎么样

vcat(transpose(x), transpose(y))

[transpose(x); transpose(y)]

最新更新