Skip to content

Commit 34e2b7f

Browse files
committed
I::CartesianIndices .+ j::CartesianIndex -> ::CartesianIndices
1 parent 6b2d211 commit 34e2b7f

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

NEWS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ Standard library changes
2626
------------------------
2727

2828
* `CartesianIndices` can now be constructed from two `CartesianIndex`es `I` and `J` with `I:J` ([#29440]).
29+
* `CartesianIndices` support broadcasting arithmetic (+ and -) with a `CartesianIndex` ([#29890]).
2930
* `copy!` support for arrays, dicts, and sets has been moved to Base from the Future package ([#29173]).
3031
* Channels now convert inserted values (like containers) instead of requiring types to match ([#29092]).
3132
* `range` can accept the stop value as a positional argument, e.g. `range(1,10,step=2)` ([#28708]).

base/broadcast.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1006,6 +1006,18 @@ broadcasted(::DefaultArrayStyle{1}, ::typeof(big), r::StepRange) = big(r.start):
10061006
broadcasted(::DefaultArrayStyle{1}, ::typeof(big), r::StepRangeLen) = StepRangeLen(big(r.ref), big(r.step), length(r), r.offset)
10071007
broadcasted(::DefaultArrayStyle{1}, ::typeof(big), r::LinRange) = LinRange(big(r.start), big(r.stop), length(r))
10081008

1009+
## CartesianIndices
1010+
broadcasted(::typeof(+), I::CartesianIndices{N}, j::CartesianIndex{N}) where N =
1011+
CartesianIndices(map((rng, offset)->rng .+ offset, I.indices, Tuple(j)))
1012+
broadcasted(::typeof(+), j::CartesianIndex{N}, I::CartesianIndices{N}) where N =
1013+
I .+ j
1014+
broadcasted(::typeof(-), I::CartesianIndices{N}, j::CartesianIndex{N}) where N =
1015+
CartesianIndices(map((rng, offset)->rng .- offset, I.indices, Tuple(j)))
1016+
function broadcasted(::typeof(-), j::CartesianIndex{N}, I::CartesianIndices{N}) where N
1017+
diffrange(offset, rng) = range(offset-last(rng), length=length(rng))
1018+
Iterators.reverse(CartesianIndices(map(diffrange, Tuple(j), I.indices)))
1019+
end
1020+
10091021
## In specific instances, we can broadcast masked BitArrays whole chunks at a time
10101022
# Very intentionally do not support much functionality here: scalar indexing would be O(n)
10111023
struct BitMaskedBitArray{N,M}

test/abstractarray.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -909,6 +909,11 @@ end
909909
J1, J2 = @inferred(promote(I1, I2))
910910
@test J1 === J2
911911
end
912+
913+
i = CartesianIndex(17,-2)
914+
@test CR .+ i === i .+ CR === CartesianIndices((19:21, -1:3))
915+
@test CR .- i === CartesianIndices((-15:-13, 3:7))
916+
@test collect(i .- CR) == Ref(i) .- collect(CR)
912917
end
913918

914919
@testset "issue #25770" begin

0 commit comments

Comments
 (0)