简体   繁体   English

重复数组行指定次数

[英]Repeat array rows specified number of times

New to julia, so this is probably very easy. julia 的新手,所以这可能非常简单。

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.我有一个 n×m 数组和一个长度为 n 的向量,我想在向量的相应元素中重复数组的每一行的次数。 For example:例如:

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

The result should be a 6-by-6 array.结果应该是一个 6×6 数组。 I tried the repeat function but我试过repeat function 但是

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.产生一个6×18×1 Array{Float64,3}: array 相反,它需要v作为重复元素的维度。 In matlab I would use repelem(mat, v, 1) and I hope julia offers something similar.在 matlab 中,我会使用repelem(mat, v, 1) ,我希望 julia 提供类似的东西。 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.我的实际矩阵要大得多,我将不得不多次调用 function,所以这个操作需要尽可能快。

It has been discussed to add a similar thing to Julia Base, but currently it is not implemented yet AFAIK.已经讨论过向 Julia Base 添加类似的东西,但目前尚未实现 AFAIK。 You can achieve what you want using the inverse_rle function from StatsBase.jl:您可以使用 StatsBase.jl 中的inverse_rle function 实现您想要的:

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). (第二个选项创建一个视图,如果您说您的mat很大并且您需要多次进行此类索引 - 哪个选项更快将取决于您的具体用例),则该视图可能与您的用例相关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM