Replacing all NaN with zeros without a loop throughout the matrix?

I had the idea to replace all NaNs in my matrix by going through each of them and using isnan. However, I suspect this will make my code run slower than necessary. Can anyone give a better suggestion?

+8
matlab
source share
3 answers

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 as follows:

 A(isnan(A)) = 0; 

Then your conclusion will be:

 A = 0 1 6 3 5 0 4 0 2 
+23
source share

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

 x( isnan(x) ) = 0 

If you do this in two steps, then it is probably better to understand what is happening. First create an array of true / false values, then use this to set the selected items to zero.

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

This is pretty simple stuff. It would be nice to read some of the MATLAB online tutorials to speed things up.

+5
source share

The isnan function isnan vectorized, which means:

 >> 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 
+4
source share

All Articles