Reputation: 939
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?
Upvotes: 10
Views: 11955
Reputation: 3640
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
Upvotes: 25
Reputation: 38042
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
Upvotes: 4
Reputation: 2125
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.
Upvotes: 5