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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With