|
Ublas : |
Subject: Re: [ublas] Question regarding sparse vector's nnz() method
From: Olaf Booij (olaf.booij_at_[hidden])
Date: 2010-03-11 04:07:29
On Thu, Mar 11, 2010 at 03:11:43AM +0000, Jesse Perla wrote:
> <al-iyaz <at> xs4all.nl> writes:
> > To the best of my knowledge nnz() indeed stands for the Number of Non Zero
> > entries of a sparse matrix. Checking boost/numeric/ublas/matrix_sparse.hpp,
> > it does seem to be implemented accordingly.
>
> One problem I ran into recently was when I was setting elements of the sparse
> matrix to be 0.0. As far as I could tell, .nnz() picked these up
> as zeros (probably as designed).... if you want to find out how many
> of the elements in the matrix are filled in with something, then use .filled()
I do not think this is the case. First of all .filled() is only defined for
ublas::coordinate_matrix and seems to have the same semantics as .nnz()
(actually returning filled_):
#include <iostream>
#include <boost/numeric/ublas/matrix_sparse.hpp>
int main()
{
typedef boost::numeric::ublas::coordinate_matrix< double > SparseMatrix;
SparseMatrix sparseMatrix(10, 10, 100);
std::cout << sparseMatrix.nnz() << " " << sparseMatrix.filled() << std::endl;
sparseMatrix(2, 4) = 1.0;
std::cout << sparseMatrix.nnz() << " " << sparseMatrix.filled() << std::endl;
sparseMatrix(4, 4) = 0.0;
std::cout << sparseMatrix.nnz() << " " << sparseMatrix.filled() << std::endl;
sparseMatrix(2, 4) = 0.0;
std::cout << sparseMatrix.nnz() << " " << sparseMatrix.filled() << std::endl;
return(0);
}
output:
0 0
1 1
2 2
2 2
Thus explicitly setting an entry to zero, does "fill in" an entry, and,
perhaps counter intuitively, accounts for a "non-zero". This is by the way
different from the behaviour of matlab. It holds for all three sparse matrix
types defined in ublas/matrix_sparse.hpp.
Olaf
edit: I now see the mail from Karl, which gives some background. I btw
prefere the behaviour of ublas over matlab.