Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

matlab

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?

like image 773

2 Answers

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
like image 119
HebeleHododo Avatar answered Nov 16 '22 02:11

HebeleHododo


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.

like image 38
Justin Avatar answered Nov 16 '22 04:11

Justin