how to replace Inf and NaN with zero using built in function

user1242199 picture user1242199 · May 7, 2012 · Viewed 40.7k times · Source

In octave, is there a build in function for replacing Inf/NaN to 0 in a vector

For example

a = log10([30 40 0 60]) => [1.4771 1.6021 -Inf 1.7782]

I can use finite or find function to find the index/position of the valid values but I don't know how to copy the values correctly without writing a function.

finite(a) => [1 1 0 1]

Answer

Gunther Struyf picture Gunther Struyf · May 7, 2012
>> a = log10([30 40 0 60])
a =
      1.477    1.602    -Inf    1.778

>> a(~isfinite(a))=0
a =
      1.477    1.602    0       1.778

does the trick, this uses logical indexing

~ is the NOT operator for boolean/logical values and isfinite(a) generates a logical vector, same size as a:

>> ~isfinite(a)
ans =
     0     0     1     0

As you can see, this is used for the logical indexing.