Selecting entries of an array based on selection criteria provided by other array

oscarvdvelde
Mon, 26 Aug 2024 16:28:25 +0000
New to Julia

Consider this example, which may run in a loop where selection is updated.

a = [1.0,1.2,0.9, 3.4, 4.5,4.5, 9.7, -1.5,-2.1]
b = [1,1,1,2,3,3,4,5,5]   # e.g. a grouping of a
selection = [1,3,5]    # these groups

# What I may naively want to do, and then e.g. median over it
julia> a[b.==selection]
ERROR: DimensionMismatch: arrays could not be broadcast to a common size; got a dimension with lengths 9 and 3

# My probably naive solution:
vcat([a[b.==s] for s in selection]...)

It must be a recipe for an excess of allocations. Is there a better way?

11 posts - 5 participants