Examples for 'Matrix::nnzero'


The Number of Non-Zero Values of a Matrix

Aliases: nnzero nnzero,ANY-method nnzero,CHMfactor-method nnzero,array-method nnzero,denseMatrix-method nnzero,diagonalMatrix-method nnzero,indMatrix-method nnzero,sparseMatrix-method nnzero,vector-method

Keywords: attribute

### ** Examples

m <- Matrix(0+1:28, nrow = 4)
m[-3,c(2,4:5,7)] <- m[ 3, 1:4] <- m[1:3, 6] <- 0
(mT <- as(m, "TsparseMatrix"))
4 x 7 sparse Matrix of class "dgTMatrix"
                      
[1,] 1 .  9 .  .  .  .
[2,] 2 . 10 .  .  .  .
[3,] . .  . . 19  . 27
[4,] 4 . 12 .  . 24  .
nnzero(mT)
[1] 9
(S <- crossprod(mT))
7 x 7 sparse Matrix of class "dsCMatrix"
                           
[1,] 21 .  77 .   .  96   .
[2,]  . .   . .   .   .   .
[3,] 77 . 325 .   . 288   .
[4,]  . .   . .   .   .   .
[5,]  . .   . . 361   . 513
[6,] 96 . 288 .   . 576   .
[7,]  . .   . . 513   . 729
nnzero(S)
[1] 13
str(S) # slots are smaller than nnzero()
Formal class 'dsCMatrix' [package "Matrix"] with 7 slots
  ..@ i       : int [1:9] 0 0 2 4 0 2 5 4 6
  ..@ p       : int [1:8] 0 1 1 3 3 4 7 9
  ..@ Dim     : int [1:2] 7 7
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num [1:9] 21 77 325 361 96 288 576 513 729
  ..@ uplo    : chr "U"
  ..@ factors : list()
stopifnot(nnzero(S) == sum(as.matrix(S) != 0))# failed earlier

data(KNex)
M <- KNex$mm
class(M)
[1] "dgCMatrix"
attr(,"package")
[1] "Matrix"
dim(M)
[1] 1850  712
length(M); stopifnot(length(M) == prod(dim(M)))
[1] 1317200
nnzero(M) # more relevant than length
[1] 8755
## the above are also visible from
str(M)
Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:8755] 0 2 25 27 163 165 1258 1261 1276 1278 ...
  ..@ p       : int [1:713] 0 13 17 26 38 43 52 56 61 67 ...
  ..@ Dim     : int [1:2] 1850 712
  ..@ Dimnames:List of 2
  .. ..$ : NULL
  .. ..$ : NULL
  ..@ x       : num [1:8755] 0.277 0.277 0.277 0.277 0.277 ...
  ..@ factors : list()

[Package Matrix version 1.5-3 Index]