Replacing all NaNs with zeros without looping through the whole matrix?

10,697

Solution 1

Let's say your matrix is:

A = 
     NaN   1       6
     3     5     NaN
     4     NaN     2

You can find the NaN elements and replace them with zero using isnan like this :

A(isnan(A)) = 0;

Then your output will be:

A =
     0     1     6
     3     5     0
     4     0     2

Solution 2

If x is your matrix then use the isnan function to index the array:

x( isnan(x) ) = 0

If you do it in two steps it's probably clearer to see what's happening. First make an array of true/false values, then use this to set selected elements to zero.

bad = isnan(x);
x(bad) = 0;

This is pretty basic stuff. You'd do well to read some of the online tutorials on MATLAB to get up to speed.

Solution 3

The function isnan is vectorized, meaning:

>> A = [[1;2;NaN; 4; NaN; 8], [9;NaN;12; 14; -inf; 28 ]]
A =
     1     9
     2   NaN
   NaN    12
     4    14
   NaN  -Inf
     8    28

>> A(isnan(A)) = 0
A =
     1     9
     2     0
     0    12
     4    14
     0  -Inf
     8    28
Share:
10,697
user1205901 - Слава Україні
Author by

user1205901 - Слава Україні

Updated on June 04, 2022

Comments

  • user1205901 - Слава Україні
    user1205901 - Слава Україні almost 2 years

    I had an idea to replace all the NaNs in my matrix by looping through each one and using isnan. However, I suspect this will make my code run more slowly than it should. Can someone provide a better suggestion?

  • rayryeng
    rayryeng almost 7 years
    Wow, there was a 3 second difference between your answer and the accepted one... the vote differential!