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?
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.
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.
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)] .
N = nnz( X ) returns the number of nonzero elements in matrix X .
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With