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

前端 未结 3 656
臣服心动
臣服心动 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: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.

提交回复
热议问题