正如@2419 所写,x=[1 2 3 4 5 6] 所得到的实际上是一个单行矩阵,而 Julia 使用列向量的性能更高。
也就是说,矩阵当然有合法用途;-)
长话短说..当您有一个矩阵并将其切片以使结果为单行时,它会自动转换为列向量:
julia> x = [1 2 3 4; 10 20 30 40; 100 200 300 400]
3×4 Matrix{Int64}:
1 2 3 4
10 20 30 40
100 200 300 400
julia> a = x[2,:]
4-element Vector{Int64}:
10
20
30
40
但是,如果将其分割为 2 行或更多行,它仍然是一个矩阵:
julia> b = x[[2,3],:]
2×4 Matrix{Int64}:
10 20 30 40
100 200 300 400
我对这个选择感到有些困惑,但就是这样,现在不会改变。
请注意,使用第一种情况检索行向量非常容易:
julia> transpose(a) # or, equivalently, `a'`
1×4 transpose(::Vector{Int64}) with eltype Int64:
10 20 30 40
重要! transpose 是一种矩阵运算,仅适用于数值矩阵(或向量)。
如果您的矩阵包含非数字元素(如字符串),transpose 会产生错误,您应该改用permutedims:
julia> x2 = [1 2 "c" 4; 10 20 "cc" 40; 100 200 300 "ddd"]
3×4 Matrix{Any}:
1 2 "c" 4
10 20 "cc" 40
100 200 300 "ddd"
julia> a2 = x2[2,:]
4-element Vector{Any}:
10
20
"cc"
40
julia> transpose(a2)
1×4 transpose(::Vector{Any}) with eltype Any:
Error showing value of type LinearAlgebra.Transpose{Any, Vector{Any}}:
ERROR: MethodError: no method matching transpose(::String)
# [...]
julia> permutedims(a2)
1×4 Matrix{Any}:
10 20 "cc" 40
不过transpose 更快:
julia> using BenchmarkTools
julia> @btime transpose(a)
21.971 ns (1 allocation: 16 bytes)
1×4 transpose(::Vector{Int64}) with eltype Int64:
10 20 30 40
julia> @btime permutedims(a)
66.289 ns (2 allocations: 96 bytes)
1×4 Matrix{Int64}:
10 20 30 40
所以,如果你确定你的矩阵是数字的,使用transpose,否则使用permutedims。