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
user85109
source share