Julia 中的多范围索引

问题描述 投票:0回答:1

我有一个问题,我想使用 Julia 索引多个范围。

我有一些变数:

idx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
fac = [[1,2,3], [4,5]]
n = 5
f = 2
z = 2

我希望当 f = 1 时输出为 1,2,3,6,7,8 当 f = 2 时,我希望输出为 4,5,9,10。

我正在考虑这方面的事情,但以我有限的知识,我不确定该怎么做:

for i = 1:f
    idx[fac[i:i]: n:10]
end
indexing julia
1个回答
0
投票

这样做的一种方法是:

@assert length(idx) % n == 0
for i in 1:f
  arr = vcat((p[fac[i]] for p in Iterators.partition(idx, n))...)
  # do something with arr
end

第一行确保

idx
数组可以安全地划分为长度为
n
的部分。然后
Iterators.partition
创建这些部分并让我们迭代它们,然后
p[fac[i]]
从每个部分中提取所需的段。
vcat
是“垂直连接”,例如将
[1, 2, 3]
[6, 7, 8]
连接在一起形成
[1, 2, 3, 6, 7, 8]

© www.soinside.com 2019 - 2024. All rights reserved.