Cartesian indices, linear indices, and sparse matrices

Thanks for writing this up as a comprehensive question!

  1. It’d probably be nice to add a sparse method that takes arrays of CartesianIndexes. Here’s a simple implementation that could serve you in the mean-time:

    function SparseArrays.sparse(IJ::Vector{<:CartesianIndex}, v, m, n)
        IJ′ = reinterpret(Int, reshape(IJ, 1, :))
        return sparse(view(IJ′, 1, :), view(IJ′, 2, :), v, m, n)
    end
    
  2. In the above I used reinterpret and lazy views to prevent needlessly allocating new vectors that contain just those “sub” indices you’re after. But you can use comprehensions to great effect to do this more simply than your for loop:

    julia> [i[1] for i in idx]
    3-element Array{Int64,1}:
     1
     4
     3
    
    julia> [i[2] for i in idx]
    3-element Array{Int64,1}:
     2
     3
     4
    
  3. To apply a function to transform the cartesian index, I’d just work directly at the level of the cartesian index. E.g.,

    julia> f(ind) = CartesianIndex(ind[1]÷2+1, ind[2]÷2+1)
    f (generic function with 1 method)
    
    julia> [f(i) for i in idx]
    3-element Array{CartesianIndex{2},1}:
     CartesianIndex(1, 2)
     CartesianIndex(3, 2)
     CartesianIndex(2, 3)
    
    julia> f.(idx) # Or just use broadcasting to the same effect
    3-element Array{CartesianIndex{2},1}:
     CartesianIndex(1, 2)
     CartesianIndex(3, 2)
     CartesianIndex(2, 3)
    
4 Likes