a = [1,3,2,4,1,2,1];
is = sortperm(a);
after this, I’d assume is[searchsorted(is, q, by=x -> a[x])]
should work to find indices in a that contain q, however:
a[is[searchsorted(is, 3, by=x -> a[x])]]
2-element Array{Int64,1}:
2
2
and similar queries somehow mess up. I might be missing something very simple but i feel quite stuck
works well with searchsorted(a[is], q)
I think that the implementation assumes that modifier keywords don’t break the ordering (otherwise, you can’t use binary search). See ?searchsorted
.
Your searchsorted
has a by
clause, so you’re searching for indices of is
that give the same value as 3
after you apply the function x->a[x]
, i.e. you’re searching for all the indices where a[is]=a[3]=2
. This correctly returns the interval 4:5
. So
a[is[searchsorted(is, 3, by=x -> a[x])]]=a[is[4:5]]=a[[3,6]]=[2,2]
2 Likes
Oooh. I assumed that the query (x=3 here) does not go through the by function. Thank you.
Is there a built in function with this behavior?
just to share, I found what I wanted, this way, using view
:
a = [1,3,2,4,1,2,1];
is = sortperm(a);
va = view(a, is)
a[is[searchsorted(va, 3)]]
1 Like