0

I have a matrix A = [0 3 4; 5 0 6; 0 6 0];

I know that to compute the total number of zero elements, I can simply use the function find. That is, Total_number_of_zero_elements = length(find(A==0)); and this will give me 4.

PROBLEM:

Take for example now the matrix B generated as follows:

B = toeplitz(0.1.^(0:30-1));
Total_number_of_zero_elements = length(find(B==0));

The code above will give: Total_number_of_zero_elements = 0. The matrix B contains a lot of 0 values but are written as 0.0000.

So matlab can't discriminate between 0 and 0.0000 using the function find?

Any help will be very appreciated!

Christina
  • 903
  • 16
  • 39

1 Answers1

5

Floating-point numbers have the property that they are not represented exactly. If you numerically multiply a matrix with its inverse, the off-diagonal elements won't be 0, but around eps(1).

In order to check the zero-ness of floats, use a threshold: find(abs(B)<1e-10). (Note the abs: without that -10 would also qualify as 0.)

Obviously the threshold should be chosen carefully: large enough that numerical zeros are caught, but small enough to let actual nonzeros stay nonzero.

In your example

B = toeplitz(0.1.^(0:30-1));

the smallest number is 1e-29, which is easily representable as a double-precision number, and it's obviously not equal to 0. If you do this further, you'll bump into problems starting around eps(0), which is roughly 5e-324. Any number larger than that will not be exactly zero. (But if you perform computations and expect the result to be 0, then it will likely be on the order of eps(1) as I wrote above.)