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


Attempts to find position of nonzero elements of a row

The obvious solution is not to work with a sparse array




does not work.

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


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


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


tells me that they do exist.



1 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];

(* {{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:




It will be obvious for people familiar with sparse arrays, but it may be good to point out that this actually gives the positions of non-default elements. The default element may be something other than zero.
– Szabolcs
Sep 2 at 13:48



@Szabolcs Right. I was thinking to point out that, but it was emphasized in the linked answer of Mr.Wizard. I added a note…
– Anton Antonov
Sep 2 at 13:49