首页 > 解决方案 > Julia CartesianIndex 到整数 LinearIndex 的转换

问题描述

要将 CartesianIndex 转换为CartesianIndex(1,2)LinearIndex,我可以使用 LinearIndeces 函数

julia> a = rand(2,2)
2×2 Array{Float64,2}:
 0.57097   0.0647051
 0.767868  0.531104

julia> I = LinearIndices(a)
2×2 LinearIndices{2,Tuple{Base.OneTo{Int64},Base.OneTo{Int64}}}:
 1  3
 2  4

julia> I[CartesianIndex(1,2)]
3

但是,如何在3CartesianIndex(1,2)构造数组实例的情况下获得 LinearIndex 整数a?假设我知道 CartesianIndex 的范围,1:2, 1:2.

标签: indexingjulia

解决方案


只需使用LinearIndices一个轴元组(甚至只是一个维度大小的元组):

julia> LinearIndices((1:2,1:2))
2×2 LinearIndices{2,Tuple{UnitRange{Int64},UnitRange{Int64}}}:
 1  3
 2  4

julia> LinearIndices((1:2,1:2))[1,2]
3

推荐阅读