【问题标题】:Julia - using CartesianIndices with an arrayJulia - 使用带有数组的 CartesianIndices
【发布时间】:2020-08-17 18:28:09
【问题描述】:

我正在尝试访问 NxN 矩阵“msk”的特定元素,索引存储在 Mx2 数组“idx”中。我尝试了以下方法:

N = 10
msk = zeros(N,N)
idx = [1 5;6 2;3 7;8 4]
#CIs = CartesianIndices(( 2:3, 5:6 )) # this works, but not what I want
CIs = CartesianIndices((idx[:,1],idx[:,2]))
msk[CIs] .= 1

我得到以下信息:错误:LoadError:MethodError:没有方法匹配 CartesianIndices(::Tuple{Array{Int64,1},Array{Int64,1}})

【问题讨论】:

  • 如果您可以控制索引的存储方式,则可以非常干净地编码。例如,如果ind = [(1,5), (6,2), (3,7), (8,4)],那么您的笛卡尔索引就是CartesianIndex.(ind)。如果您对索引矩阵感到困惑,则必须使用更复杂的解决方案 eachcol

标签: indexing julia


【解决方案1】:

这是你想要的吗? (我正在使用你的定义)

julia> msk[CartesianIndex.(eachcol(idx)...)] .= 1;

julia> msk
10×10 Array{Float64,2}:
 0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0  1.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  1.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0
 0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0  0.0

注意我使用了CartesianIndex的向量:

julia> CartesianIndex.(eachcol(idx)...)
4-element Array{CartesianIndex{2},1}:
 CartesianIndex(1, 5)
 CartesianIndex(6, 2)
 CartesianIndex(3, 7)
 CartesianIndex(8, 4)

因为CartesianIndices 是:

定义一个区域 R 跨越整数索引的多维矩形范围。

所以它定义的区域必须是矩形的。

获取所需索引的另一种方法是例如:

julia> CartesianIndex.(Tuple.(eachrow(idx)))
4-element Array{CartesianIndex{2},1}:
 CartesianIndex(1, 5)
 CartesianIndex(6, 2)
 CartesianIndex(3, 7)
 CartesianIndex(8, 4)

或者(这次我们使用线性索引到msk,因为它只是一个Matrix

julia> [x + (y-1)*size(msk, 1) for (x, y) in eachrow(idx)]
4-element Array{Int64,1}:
 41
 16
 63
 38

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2023-02-11
    • 2016-06-13
    • 2020-10-01
    相关资源
    最近更新 更多