Skip to main content

sparse arrays - How to find position of non-zero elements in SparseArray without converting to a dense object



So I have a SparseArray, sparse, constructed from a list of rules, with the dimension options. Given a row, I want to know where the values are non-zero. Finding what those values are is easy, but where is harder...


How the SparseArray was made


listOfRules = {{1,1} -> 3, {4,30} -> 4 ... };
sparse = SparseArray[listOfRules,{n,n}];


Find non-zero values in a row


Select[sparse[[rowNumber]],#!=0&]

Attempts to find position of nonzero elements of a row


The obvious solution is not to work with a sparse array


Flatten[Position[Normal[sparse[[rowNumber]]],n_Integer/;n>0]]

Unfortunalely


Position[sparse[[rowNumber]],n_Integer/;n>0]


does not work.


Interestingly the pure function works for with the function Select, but not Position, e.g.


Position[Normal[sparse[[rowNumber]]],#!=0]

returns nothing. Whereas the pattern works for the function Position but not Select


Select[sparse[[rowNumber]], n_Integer /; n > 0]

Neither Keys or Values work either... which I thought might, since it is built off a list of rules.


Oh and the obvious


Select[sparse[[rowNumber]],aNumber]

Position[sparse[[rowNumber,aNumber]

do not work either, although I know that there is an element with that value because


 Select[sparse[[rowNumber]],#!=0&]

tells me that they do exist.



Answer



(Posting as an answer since it seems too long to be a comment.)


The answer to your question is in the answer of this question "What are SparseArray Properties? How and when should they be used?".


One of the examples in the referred answer is:



a = {{1, 0, 2}, {0, 0, 1}, {2, 0, 1}};
sa0 = SparseArray[a];
sa0["NonzeroPositions"]

(* {{1, 1}, {1, 3}, {2, 3}, {3, 1}, {3, 3}} *)

Note that "NonzeroPositions" returns the position of every non-background element in the sparse array.


Another option is to use:


sa0["AdjacencyLists"]

Comments