Julia数组的索引集合缩写:

huangapple go评论56阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月11日 04:55:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76657289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定