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

前端 未结 3 651
臣服心动
臣服心动 2020-12-06 17:42

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

相关标签:
3条回答
  • 2020-12-06 18:00

    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
    
    0 讨论(0)
  • 2020-12-06 18:13

    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
    
    0 讨论(0)
  • 2020-12-06 18:13

    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.

    0 讨论(0)
提交回复
热议问题