2
votes

I am trying to access specific elements of an NxN matrix 'msk', with indices stored in a Mx2 array 'idx'. I tried the following:

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

I get the following: ERROR: LoadError: MethodError: no method matching CartesianIndices(::Tuple{Array{Int64,1},Array{Int64,1}})

1
If you have any control over how the indices are stored this can be coded very cleanly. For example, if ind = [(1,5), (6,2), (3,7), (8,4)], then your cartesian indices are just CartesianIndex.(ind). If you are a stuck with a matrix of indices, you have to use the more convoluted solution with eachcol.DNF

1 Answers

2
votes

Is this what you want? (I am using your definitions)

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

Note that I use a vector of CartesianIndex:

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

as CartesianIndices is:

Define a region R spanning a multidimensional rectangular range of integer indices.

so the region defined by it must be rectangular.

Another way to get the required indices would be e.g.:

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

or (this time we use linear indexing into msk as it is just a Matrix)

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