英文:
Julia abbreviation for index set of array
问题
以下是翻译好的部分:
考虑两个不同大小的矩阵
julia> A = ones(Float64, 3, 3)
3x3 Matrix{Float64}:
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
julia> B = ones(Float64, 2, 2)
2x2 Matrix{Float64}:
1.0 1.0
1.0 1.0
是否有一种缩写表示法可以代替
julia> A[1:size(B)[1], 1:size(B)[2]]
2x2 Matrix{Float64}:
1.0 1.0
1.0 1.0
以一种类似于" julia> A[indices(B)]
"这样的美观函数形式(不幸的是,该函数不存在 ERROR: UndefVarError: indices not defined
)?
英文:
Consider two matrices of different size
julia> A= ones(Float64,3,3)
3×3 Matrix{Float64}:
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
julia> B = ones(Float64,2,2)
2×2 Matrix{Float64}:
1.0 1.0
1.0 1.0
Is there a shorthand notation for
julia> A[1:size(B)[1],1:size(B)[2]]
2×2 Matrix{Float64}:
1.0 1.0
1.0 1.0
in the form of a nice function like "julia> A[indices(B)]
" (which unfortunately does not exist ERROR: UndefVarError: indices not defined
)?
答案1
得分: 6
你可以调用 axes(B)
来获取包含 B
有效索引的元组:
julia> A = ones(3, 3)
3×3 Float64 矩阵:
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
julia> B = ones(2, 2)
2×2 Float64 矩阵:
1.0 1.0
1.0 1.0
julia> axes(B)
(Base.OneTo(2), Base.OneTo(2))
因此,你可以解包这个元组并用它来索引 A
:
julia> A[axes(B)...]
2×2 Float64 矩阵:
1.0 1.0
1.0 1.0
正如Bogumil Kaminski在评论中指出的,你还可以使用 CartesianIndices
:
julia> A[CartesianIndices(B)]
2×2 Float64 矩阵:
1.0 1.0
1.0 1.0
英文:
You can call axes(B)
to get a tuple containing the valid indices for B
:
julia> A = ones(3, 3)
3×3 Matrix{Float64}:
1.0 1.0 1.0
1.0 1.0 1.0
1.0 1.0 1.0
julia> B = ones(2, 2)
2×2 Matrix{Float64}:
1.0 1.0
1.0 1.0
julia> axes(B)
(Base.OneTo(2), Base.OneTo(2))
Thus, you can unpack the tuple and use it for indexing A
:
julia> A[axes(B)...]
2×2 Matrix{Float64}:
1.0 1.0
1.0 1.0
As Bogumil Kaminski pointed out in the comments, you can also use CartesianIndices
:
julia> A[CartesianIndices(B)]
2×2 Matrix{Float64}:
1.0 1.0
1.0 1.0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论