Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
1  
GatherBy[SparseArray[m]["NonzeroPositions"], First][[All, All, 2]] – J. M. Mar 27 at 23:59
    
or (SparseArray[#]["NonzeroPositions"] & /@ m)[[;; , ;; , 1]] – garej Mar 28 at 6:15
up vote 9 down vote accepted

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

share|improve this answer

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

Pick[Range@Length@m[[1]], #, 0] & /@ UnitStep@-m
share|improve this answer

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

SplitBy[ SparseArray[m]["NonzeroPositions"], First][[All, 2]]
 {{1, 2}, {2, 3}}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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