TL;DR:我試圖理解為什么 Matrixes 不能索引 Julia 中的 Vector 物件。顯然,一個向量可以索引一個矩陣(見下文),但反過來是不合法的。我想了解這種行為,因為(1)我不明白它為什么會發生,(2)我認為這可以防止程式員把事情搞砸,但我看不出這種行為在保護程式員免受什么侵害。非常感謝你。
考慮以下陣列。
julia> x_vector = [3 ; 2 ; 1]
3-element Vector{Int64}:
3
2
1
julia> x_matrix = [3 ; 2 ; 1;;]
3×1 Matrix{Int64}:
3
2
1
julia> y_vector = [1 ,0 ,0]
3-element Vector{Int64}:
1
0
0
julia> y_matrix = [1; 0; 0;;]
3×1 Matrix{Int64}:
1
0
0
現在,我將使用y陣列來索引x陣列,選擇陣列中包含 1 的值y。
下面我列出了一些瑣碎的情況(即矩陣索引矩陣和向量索引向量)
julia> x_matrix[isone.(y_matrix)]
1-element Vector{Int64}:
3
julia> x_matrix[isone.(y_vector)]
1-element Vector{Int64}:
3
顯然,我可以使用向量來索引矩陣。
julia> x_matrix[isone.(y_vector)]
1-element Vector{Int64}:
3
但是,我不能使用矩陣來索引向量,即使它們具有相同的維度(是嗎?)。
x_vector[isone.(y_matrix)]
ERROR: BoundsError: attempt to access 3-element Vector{Int64} at index [3×1 BitMatrix]
Stacktrace:
[1] throw_boundserror(A::Vector{Int64}, I::Tuple{Base.LogicalIndex{Int64, BitMatrix}})
@ Base .\abstractarray.jl:691
[2] checkbounds
@ .\abstractarray.jl:656 [inlined]
[3] _getindex
@ .\multidimensional.jl:838 [inlined]
[4] getindex(A::Vector{Int64}, I::BitMatrix)
@ Base .\abstractarray.jl:1218
[5] top-level scope
@ C:\Users\index_matrix_vector.jl:34
[6] eval
@ .\boot.jl:373 [inlined]
uj5u.com熱心網友回復:
如果您使用整數索引,則允許將矩陣傳遞給索引:
julia> a = [1, 2, 3]
3-element Vector{Int64}:
1
2
3
julia> m = [1 2
3 1]
2×2 Matrix{Int64}:
1 2
3 1
julia> a[m]
2×2 Matrix{Int64}:
1 2
3 1
但是,在您的示例中,您使用了Bool索引,這很特別,您可以在https://docs.julialang.org/en/v1/manual/arrays/#Logical-indexing中查看。
如您所見:
邏輯索引必須是與其索引到的維度相同長度的向量,或者它必須是提供的唯一索引并且匹配它索引到的陣列的大小和維度。
此限制遵循您已發出信號的邏輯 - 這是為了安全。現在你可能會問為什么對于高維陣列,向量和陣列索引都是允許的。
我對原因的理解是,這在概念上與 Julia 中的陣列被允許索引的兩種方式相匹配:
- 線性索引(在索引時傳遞一個數字) - 這映射到
Bool在您的情況下使用向量的索引 - 普通索引(您傳遞的索引與陣列中的維度一樣多) - 此映射與索引的陣列的
Bool形狀匹配索引陣列的形狀。Bool您可以 - 正如檔案所述,分別為陣列的每個維度傳遞索引向量
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/425123.html
