I would like to calculate number of elements in a matrix that are equal to Zero or One. The goal is calculate density of elements in a matrix that are equal to zero or one. I use this to calculate sparseness of the matrix as well.
Generally in Sparse matrix, majority of the elements are ZEROs. But in the matrix I privided has very few Zero and Ones and elements having value 'X' are more in number. Hence I would like to find count of elements having zero and one first. Then I shall use them to calculate Sparseness and Sparse density of the matrix.
The matrix looks like:
\begin{matrix} 1 & 0 & x & x & x & x & 0 & x & x & x & 0 & x & x & x & x & x & x & x\\ x & x & x & x & 0 & x & x & x & x & x & x & x & x & x & 1 & x & x & 0\\ 0 & x & x & x & x & 1 & x & x & x & x & x & 0 & x & x & x & x & x & x\\ \end{matrix}
If I understand the question correctly, the goal is to count the number of elements in a matrix that are equal to zero or one. There are a few ways to answer this.
For arbitrary matrices, the only way is to inspect each element and count manually. Zero and one are not special values in matrices, so there aren't special operations to extract a count. In fact, since it was mentioned that the matrix values come from electronics, the values of the matrix elements will not in general be integers. So, the check for zero and one would look more like $|x| < \epsilon$ for zero and $|x-1| < \epsilon$ for one with $\epsilon$ being some small constant. This is to handle floating point uncertainties in software.
Now, if the matrix has more structure, then some cleverness can be brought to bear. For example, if every element an $n \times m$-matrix $M$ is either zero or one, then the count of ones in the matrix is given by $$c_1 = \textrm{tr}(M^TM),$$ and the count of zeros is given by $$c_0 = nm - c_1,$$ where $\textrm{tr}(M)$ is the trace of $M$ and $M^T$ is the transpose of $M.$
This can be seen by noting that the diagonal elements of $M^TM$ are the dot products of the column vectors of $M$ with themselves. Also, the dot product of a binary (consisting of zeros and ones) vector with itself is equal to the number of ones in that vector.