MATLAB - replace zeros in a matrix with a small number

I have a matrix with some elements going to zero. This is a problem for me in subsequent operations (logging, etc.). Is there a way to quickly replace the null elements in a matrix by inputting my choice. Fast means no cycle.

+4
source share
3 answers

Of course - where A is your matrix,

A(A==0) = my_small_number; 
+4
source

Direct answer:

 M(M == 0) = realmin; 

which does exactly what you ask for, replacing zeros with a small number. See that this implies an implicit search for zeros in vector form. No cycles. (This is the MATLAB path, avoiding these explicit and slow loops.)

Or you can use max, since negative numbers are never a problem. So

 M = max(M,realmin); 

will also work. Again, this is a vector solution. Iโ€™m not sure if itโ€™s faster without a thorough test, but it will certainly be acceptable.

Note that I used realmin here instead of eps, as it is as small as you can actually get a double precision number. But using any small amount makes sense to you.

 log10(realmin) ans = -307.6527 

Compare this to eps.

 log10(eps) ans = -15.6536 
+5
source

Suppose your matrix is โ€‹โ€‹called A

 A(A==0) = eps; 
+3
source

Source: https://habr.com/ru/post/1484694/


All Articles