Nonzero element positions of a matrix
Update: The property "AdjacencyLists"
gives what you need:
SparseArray[m]["AdjacencyLists"]
{{1, 2}, {1, 3}}
This approach, unlike the one using GatherBy
in the original post, gives the empty set {}
for the rows consisting entirely of zeros:
SparseArray[{{1, 2, 0}, {0, 0, 0}, {4, 0, 9}}]["AdjacencyLists"]
{{1, 2}, {}, {1, 3}}
Original post:
m = {{1, 2, 0}, {4, 0, 9}};
sa = SparseArray[m]["NonzeroPositions"];
GatherBy[sa, First][[All, All, -1]]
{{1, 2}, {1, 3}}
If the matrix isn't that sparse, then Pick
may be a more efficient idea:
Pick[Range@Length@m[[1]], #, 0] & /@ UnitStep@-m