Bel
Bel

Reputation: 33

Matlab function NNZ, numerical zero

I am working on a code in Least Square Non Negative solution recovery context on Matlab, and I need (with no more details because it's not that important for this question) to know the number of non zero elements in my matrices and arrays.

The function NNZ on matlab does exactly what I want, but it happens that I need more information about what Matlab thinks of a "zero element", it could be 0 itself, or the numerical zero like 1e-16 or less.

Does anybody has this information about the NNZ function, cause I couldn't get the original script

Thanks.

PS : I am not an expert on Matlab, so accept my apologies if it's a really simple task.

I tried "open nnz", on Matlab but I only get a small script of commented code lines...

Upvotes: 3

Views: 407

Answers (2)

gnovice
gnovice

Reputation: 125864

Since nnz counts everything that isn't an exact zero (i.e. 1e-100 is non-zero), you just have to apply a relational operator to your data first to find how many values exceed some tolerance around zero. For a matrix A:

n = nnz(abs(A) > 1e-16);

Also, this discussion of floating-point comparison might be of interest to you.

Upvotes: 3

John
John

Reputation: 2127

You can add in a tolerance by doing something like:

nnz(abs(myarray)>tol);

This will create a binary array that is 1 when abs(myarray)>tol and 0 otherwise and then count the number of non-zero entries.

Upvotes: 2

Related Questions