Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error when using in(::T, ::StepRangeLen{T,T,T,Int}) where {T<:CartesianIndex{2}} #57034

Open
lkdvos opened this issue Jan 13, 2025 · 0 comments

Comments

@lkdvos
Copy link

lkdvos commented Jan 13, 2025

When working with LinearAlgebra.diagind(::Diagonal, ::IndexCartesian) I bumped into the following error:

using LinearAlgebra
d = Diagonal(rand(3));
r = diagind(d, IndexCartesian()) # StepRangeLen(CartesianIndex(1, 1), CartesianIndex(1, 1), 3)
CartesianIndex(1,1) in diagind(d, IndexCartesian()) # errors

produces (both on 1.11.2 and nightly)

ERROR: MethodError: no method matching /(::CartesianIndex{2}, ::CartesianIndex{2})
The function `/` exists, but no method is defined for this combination of argument types.

Closest candidates are:
  /(::BigInt, ::BigInt)
   @ Base gmp.jl:517
  /(::BigInt, ::Union{Int16, Int32, Int64, Int8, UInt16, UInt32, UInt64, UInt8})
   @ Base gmp.jl:566
  /(::ComplexF64, ::ComplexF64)
   @ Base complex.jl:397
  ...

Stacktrace:
 [1] _in_range
   @ ./range.jl:1434 [inlined]
 [2] in(x::CartesianIndex{2}, r::StepRangeLen{CartesianIndex{2}, CartesianIndex{2}, CartesianIndex{2}, Int64})
   @ Base ./range.jl:1440

I can fix this in a similar way to base by adding a specialized function:

function _in_range(x::CartesianIndex{N}, r::AbstractRange{CartesianIndex{N}}) where {N}
    isempty(r) && return false
    for i in 1:N
        f, l = first(r)[i], last(r)[i]
        # check for NaN, Inf, and large x that may overflow in the next calculation
        f <= x[i] <= l || l <= x[i] <= f || return false
    end

    i = findfirst(!iszero, step(r).I)
    isnothing(i) && return true

    n = round(Integer, (x[i] - first(r)[i]) / step(r)[i]) + 1
    return n  1 && n  length(r) && r[n] == x
end

but I wanted to check first if this is the preferred way to do this (and where that function should go)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant