2
$\begingroup$

Overview

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.

$\endgroup$
7
$\begingroup$

(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"]
$\endgroup$
  • 1
    $\begingroup$ 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. $\endgroup$ – Szabolcs Sep 2 '16 at 13:48
  • $\begingroup$ @Szabolcs Right. I was thinking to point out that, but it was emphasized in the linked answer of Mr.Wizard. I added a note... $\endgroup$ – Anton Antonov Sep 2 '16 at 13:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.