3
votes

New to julia, so this is probably very easy.

I have an n-by-m array and a vector of length n and want to repeat each row of the array the number of times in the corresponding element of the vector. For example:

mat = rand(3,6)
v = vec([2 3 1])

The result should be a 6-by-6 array. I tried the repeat function but

repeat(mat, inner = v)

yields a 6×18×1 Array{Float64,3}: array instead so it takes v to be the dimensions along which to repeat the elements. In matlab I would use repelem(mat, v, 1) and I hope julia offers something similar. My actual matrix is a lot bigger and I will have to call the function many times, so this operation needs to be as fast as possible.

1

1 Answers

5
votes

It has been discussed to add a similar thing to Julia Base, but currently it is not implemented yet AFAIK. You can achieve what you want using the inverse_rle function from StatsBase.jl:

julia> row_idx = inverse_rle(axes(v, 1), v)
6-element Array{Int64,1}:
 1
 1
 2
 2
 2
 3

and now you can write:

mat[row_idx, :]

or

@view mat[row_idx, :]

(the second option creates a view which might be relevant in your use case if you say that your mat is large and you need to do such indexing many times - which option is faster will depend on your exact use case).