在Base中有一种简单的方法来枚举数组的索引吗?

huangapple go评论58阅读模式
英文:

Is there a simple way to enumerate indices of an Array in Base?

问题

有时候,人们想要遍历数组的索引。例如,假设我想创建一个带有噪声的乘法表。首先,创建一些噪声:

julia> m = 0.1*rand(2,3)
2×3 Matrix{Float64}:
0.0692654 0.0297861 0.0642931
0.0187022 0.0530222 0.0561437

接下来,添加表的值:

julia> indices(A) = Iterators.map(Tuple, CartesianIndices(A))
indices (generic function with 1 method)

julia> noisy_mult = [i*j+m[i,j] for (i,j) in indices(m)]
2×3 Matrix{Float64}:
1.06927 2.02979 3.06429
2.0187 4.05302 6.05614

英文:

Sometimes one wants to loop over the indices of an Array. For example, suppose I want to create a noisy multiplication table. First, create some noise:

julia> m = 0.1*rand(2,3)
2×3 Matrix{Float64}:
 0.0692654  0.0297861  0.0642931
 0.0187022  0.0530222  0.0561437

Next, add the values of the table:

julia> indices(A) = Iterators.map(Tuple, CartesianIndices(A))
indices (generic function with 1 method)

julia> noisy_mult = [i*j+m[i,j] for (i,j) in indices(m)]
2×3 Matrix{Float64}:
 1.06927  2.02979  3.06429
 2.0187   4.05302  6.05614

Is there an indices equivalent in Base, or a better/simpler way to achieve the same result? Will adding indices to the standard library be a good idea?

答案1

得分: 1

这似乎是针对CartesianIndices的以下错误消息的解决方法:

对于CartesianIndex,迭代是故意不支持的。
使用`I`而不是`I...`,或者使用`Tuple(I)...`

我会问问编写这个消息的人,是否存在任何添加这样一种解决方法的不利因素。

英文:

This looks like a workaround for the following error message for CartesianIndices:

iteration is deliberately unsupported for CartesianIndex. 
Use `I` rather than `I...`, or use `Tuple(I)...`

I would ask whoever wrote that message about the disadvantages if any of adding such a way around it.

huangapple
  • 本文由 发表于 2023年5月7日 08:25:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定