Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia abbreviation for index set of array

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)?

like image 293
phinz Avatar asked Oct 21 '25 03:10

phinz


1 Answers

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
like image 72
Cameron Bieganek Avatar answered Oct 23 '25 01:10

Cameron Bieganek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!