2.37 Find all nonzero elements in a matrix

Given a matrix, find the locations and the values of all nonzero elements. Hence given the matrix

\[ \left ( {\begin {array}{ccc} 0 & 0 & 1 \\ 10 & 0 & 2 \\ 3 & 0 & 0 \end {array}} \right )\]

the positions returned will be \((1,3),(2,1),(2,3),(3,1)\) and the corresponding values are \(1,10,2,3\).

Mathematica

In Mathematica, standard Mathematica matrix operations can be used, or the matrix can be converted to SparseArray and special named operation can be used on it.

mat  = {{0 , 0, 1}, 
        {10, 0, 2}, 
        {3 , 4, 0}}; 
 
sp  = SparseArray[mat]; 
pos = sp["NonzeroPositions"]
 

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

values=sp["NonzeroValues"]
 

{1,10,2,3,4}
 

Or standard list operations can be used

mat  = {{0 , 0, 1}, 
        {10, 0, 2}, 
        {3 , 4, 0}}; 
 
(*find values not zero *) 
 
Cases[mat,x_ /;Not[PossibleZeroQ[x]]:>x,2]
 

{1,10,2,3,4}
 

(*find the index *) 
 
Position[mat,x_/;x!=0]
 

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

 

Matlab

A=[0 0 1; 10 0 2; 3 4 0]; 
values= nonzeros(A)
 

values = 
    10 
     3 
     4 
     1 
     2
 

%find locations 
[I,J]=find(A)
 

I = 
     2 
     3 
     3 
     1 
     2 
J = 
     1 
     1 
     2 
     3 
     3
 

 

Maple

A:=Matrix([[0,0,1],[10,0,2],[3,4,0]]); 
row, col:=ArrayTools:-SearchArray(A); 
 
#values 
map(n->A[row[n],col[n]],[$numelems(row)])
 

row, col := Vector[column](5, [2, 3, 3, 1, 2]), 
            Vector[column](5, [1, 1, 2, 3, 3]) 
 
 
[10, 3, 4, 1, 2]