假设我有两个向量x = [1, 2]
和y = [3, 4]
。如何最好地组合它们以获得m = [1 2; 3 4]
Julia 编程语言中的矩阵?预先感谢您的支持。
Bog*_*ski 10
请注意,在vcat(x', y')
操作中x'
是伴随的,因此如果您正在处理没有定义伴随的复数或向量元素(例如字符串),则不应使用它。因此,permutedims
应该使用then ,但它在分配时会变慢。第三种方法是(不可否认,键入更麻烦):
julia> [reshape(x, 1, :); reshape(y, 1, :)]
2×2 Array{Int64,2}:
1 2
3 4
Run Code Online (Sandbox Code Playgroud)
它是非分配的,[x'; y']
但不做递归伴随。
编辑:
卡梅伦注意事项:
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)
Run Code Online (Sandbox Code Playgroud)
所以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
Run Code Online (Sandbox Code Playgroud)
我知道的两种方式:
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
Run Code Online (Sandbox Code Playgroud)
另一种选择 - 这一个适用于数字和其他对象作为String
s:
julia> rotl90([y x])
2×2 Array{Int64,2}:
1 2
3 4
Run Code Online (Sandbox Code Playgroud)
关于什么
vcat(transpose(x), transpose(y))
Run Code Online (Sandbox Code Playgroud)
或者
[transpose(x); transpose(y)]
Run Code Online (Sandbox Code Playgroud)