7
$\begingroup$

Let

m={{1, 2, 0}, {4, 0, 9}};

I want to find the position of every nonzero element of the above matrix. The code

SparseArray[m]["NonzeroPositions"]

returns

{{1, 1}, {1, 2}, {2, 1}, {2, 3}}

I want the output will be something like this

{{1, 2}, {1, 3}}

that is every element of the output is a list of the corresponding columns of nonzero elements in each row. How do I modify the code?

$\endgroup$
  • 1
    $\begingroup$ GatherBy[SparseArray[m]["NonzeroPositions"], First][[All, All, 2]] $\endgroup$ – J. M. will be back soon Mar 27 '16 at 23:59
  • $\begingroup$ or (SparseArray[#]["NonzeroPositions"] & /@ m)[[;; , ;; , 1]] $\endgroup$ – garej Mar 28 '16 at 6:15
9
$\begingroup$

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}}

$\endgroup$
2
$\begingroup$

If the matrix isn't that sparse, then Pick may be a more efficient idea:

Pick[Range@Length@m[[1]], #, 0] & /@ UnitStep@-m
$\endgroup$
1
$\begingroup$

One can use e.g. SplitBy[list, First] way:

SplitBy[ SparseArray[m]["NonzeroPositions"], First][[All, 2]]
 {{1, 2}, {2, 3}}
$\endgroup$

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.