Getindex for AbstractArray with Function

There is a AbstractArray:

m=[[1,2,3] [2,3,4]]

"""
3×2 Matrix{Int64}:
 1  2
 2  3
 3  4

"""

How can I dispath on Function to Base.getindex to have this custom method?

m[>=(2),:]

"""
1×2 Matrix{Int64}:

 2  3
 3  4

"""


m[:,>=(1)]

m[[1,2], >=(1)]

etc.....

Hi! It seems to me that you want to do something like

m[2:end, :]

is that correct?

1 Like

yes, this can get the same result.

But above is just a simple example, I have many more compcated situation, which have the similar style to that.

Maybe you could engineer something with findall instead of overloading getindex?

findall is good, but not elegent. With methods mentioned above, I can:

Base.getindex(x::M,i::F) where T=x[i.(@view(x[:,1])),:]

Base.getindex(x::V,i::F)=x[i.(x)]

Base.getindex(x::M,i::Va{Pair})=begin
    mask=trues(size(x,1))
    for (k,v) in i
        mask = mask .&& (@view(x[:,k]) .|> v)
    end
    x[mask,:]

end

m[>=(2)]

"""
2×2 Matrix{Int64}:
 2  3
 3  4

"""

m[1=>>=(2),2=>==(3)]

"""
1×2 Matrix{Int64}:
 2  3
"""

It’s hard to get a grip on what you are trying to do. For example,

julia> m[2:end, :]
2×2 Matrix{Int64}:
 2  3
 3  4

julia> m[m[:, 1].>=2, :]
2×2 Matrix{Int64}:
 2  3
 3  4

neither of which are the same. Can you explain what x[>=(2), :] is supposed to do? Why does it return [2 3]?

1 Like

Sorry for that, I made a mistake, It is supposed to

So you are looking for calculations on the indices, not on the values when selecting rows?

Maybe something like

m[foo.(axes(m, 1)), :]

for a function foo that returns a Bool. If you are working on the values, not the indices, then

m[foo.(m[:, 1]), :]

maybe with a @view in front.

I would not recommend overloading getindex for Array and Function, since that would be type piracy. Instead, you could make your own function, maybe

selectrows(f::Function, m::AbstractMatrix) = m[f.(axes(m, 1)), :]

and then, selectrows(>=(2), m), etc.

2 Likes