如何在 Julia 中索引循环数组? [英] How to index circular array in Julia?
本文介绍了如何在 Julia 中索引循环数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想以循环方式访问数组中的元素.通常模数就足够了,但在 Julia 数组中,数组从 1 开始.目前,我基本上将索引转换为基于 0 的索引并返回.但这不适用于负索引.
I'd like to access elements in an array in a circular manner. Normally a modulo suffices but in Julia arrays start at 1. At the moment I'm basically converting the indices to a 0-based index and back. But this doesn't work for negative indices.
A = 1:5
for i in -6:6
println(i, " -> ", ((i - 1) % length(A)) + 1)
end
输出
-6 -> -1 # wrong
-5 -> 0 # wrong
-4 -> 1 # wrong
-3 -> -3 # wrong
-2 -> -2 # wrong
-1 -> -1 # wrong
0 -> 0 # wrong
1 -> 1
2 -> 2
3 -> 3
4 -> 4
5 -> 5
6 -> 1
推荐答案
我通常为此使用 mod1
函数.这是一个例子:
I usually use mod1
function for this. Here is an example:
julia> [-10:10 mod1.(-10:10, 5)]
21×2 Array{Int64,2}:
-10 5
-9 1
-8 2
-7 3
-6 4
-5 5
-4 1
-3 2
-2 3
-1 4
0 5
1 1
2 2
3 3
4 4
5 5
6 1
7 2
8 3
9 4
10 5
这篇关于如何在 Julia 中索引循环数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文