Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find indices of non zero elements in matrix

Tags:

r

I want to get the indices of non zero elements in a matrix.for example

X <- matrix(c(1,0,3,4,0,5), byrow=TRUE, nrow=2); 

should give me something like this

row col 1    1 1    3 2    1 2    3 

Can any one please tell me how to do that?

like image 759
Shruti Avatar asked Jul 07 '10 07:07

Shruti


People also ask

How do you find nonzero elements in a matrix?

Location and Count of NonzerosUse nonzeros , nnz , and find to locate and count nonzero matrix elements. Create a 10-by-10 random sparse matrix with 7% density of nonzeros. A = sprand(10,10,0.07); Use nonzeros to find the values of the nonzero elements.

How do you find the indices of a matrix?

Description. k = find( X ) returns a vector containing the linear indices of each nonzero element in array X . If X is a vector, then find returns a vector with the same orientation as X . If X is a multidimensional array, then find returns a column vector of the linear indices of the result.

How do you get Numpy indices of nonzero elements?

nonzero() function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] .

How do you find the number of non-zero elements in a matrix in MATLAB?

N = nnz( X ) returns the number of nonzero elements in matrix X .


Video Answer


2 Answers

which(X!=0,arr.ind = T)      row col [1,]   1   1 [2,]   2   1 [3,]   1   3 [4,]   2   3 

If arr.ind == TRUE and X is an array, the result is a matrix whose rows each are the indices of the elements of X

like image 62
George Dontas Avatar answered Sep 19 '22 20:09

George Dontas


There's an error in your example code - True is not defined, use TRUE.

X <-matrix(c(1,0,3,4,0,5), byrow = TRUE, nrow = 2) 

which should do it:

which(!X == 0) X[ which(!X == 0)] #[1] 1 4 3 5 

to get the row/col indices:

 row(X)[which(!X == 0)]  col(X)[which(!X == 0)] 

to use those to index back into the matrix:

   X[cbind(row(X)[which(!X == 0)], col(X)[which(!X == 0)])]    #[1] 1 4 3 5 
like image 39
mdsumner Avatar answered Sep 21 '22 20:09

mdsumner