英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论