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)?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With