I will go with a minimal working example and ask questions in bold as I go through it.
Before v0.7, I had this working code:
A = sparse([1,3,4],[2,4,3], [1,2,3], 4,5)
idx = find(A)
# make a sparse matrix using subindices
idx1, idx2 = ind2sub(size(A), idx)
B = sparse(idx1, idx2, [4,5,6], 4, 5)
# transform one of the subindices and make another matrix
f(x) = (x + 2) .% 5 + 1
C = sparse(idx1, f(idx2), [7,8,9], 4, 5)
Now a few things have changed with v0.7+. First, I now need to use the SparseArrays
package and find
is deprecated, so I now start with
using SparseArrays
A = sparse([1,3,4],[2,4,3], [1,2,3], 4,5)
idx = findall(!iszero, A)
Note that idx
's type is 3element Array{CartesianIndex{2},1}
now, which leads me to my first question:

How do I create a sparse matrix
B
from an array ofCartesianIndex
and values?Currently,
B = sparse(idx, [4,5,6], 4, 5)
is not valid and raises an error.
Same goes for using linear indices:lidx = LinearIndices(A)[idx] B = sparse(lidx, [4,5,6], 4, 5)
also raises an error. So letâ€™s assume I cannot do that directly with cartesian or linear indices, then I need subindices, which leads me to my second question:

How do I access the subindices of a cartesian index array?
Right now,
idx
contains the following:3element Array{CartesianIndex{2},1}: CartesianIndex(1, 2) CartesianIndex(4, 3) CartesianIndex(3, 4)
and I would like to use the subindices
[1,4,3]
and[2,3,4]
. But theind2sub
function is deprecated, encouraging us to use theCartesianIndex
type. I could painfully access them by looping through everyCartesianIndex
:j = 0 subidx1 = zeros(Int64, length(idx)) subidx2 = copy(subidx1) for i in idx j += 1 subidx1[j] = i[1] subidx2[j] = i[2] end B = sparse(subidx1, subidx2, [4,5,6], 4,5)
But this feels â€śdirtyâ€ť to meâ€¦ I may probably be writing this the wrong way, but I wished there was a builtin way to get those sub indices. (Maybe there is?) Something like
subidx1, subidx2 = ind2sub(size(A), idx)
would be nice!

How do I apply a function to a subindex inside a cartesian index?
I may be wrong in just trying to access those subindices, but I have a need to transform one of them sometimes, by applying a function to it. Say I want to shift the second index by 3 to the right (like in the nonv0.7+ example at the start of this post), or I want to pack these indices as close to the left as possible. Again, there might be an easy way to do it, but I have not figured it out yet.
Please help