scalascala-breeze

Counting non-zero elements in a sparse matrix using breeze


I'm new to breeze. I can't seem to be able to count the number of non-zero element per row in a CSCMatrix.

Let's take the following example :

val matrix = CSCMatrix.tabulate(3, 2)((x,y) => x*y)

This is a sparse matrix of dimension 3x2:

|0|0|
|0|1|
|0|2|

What I want is to compute the number of non-zero elements per row, so the output should be a vector of the form:

|0|
|1|
|1|

It would be easy to do it with numpy, but I can't seem to be able to do it with breeze.


Solution

  • In case someone still needs this, you may do it with a Matrix vector multiplication in the following way:

    matrix * DenseVector.ones[Int](matrix.cols)