Is there any general way to remove NaNs from a matrix? Sometimes I come across this problem in the middle of some code and then it creates problems to get appropriate outputs. Is there any way to generate any kind of check to avoid NaNs arising in a MATLAB code? It will be really helpful if someone can kindly give me an example with some idea related to it.
问题:
回答1:
You can detect nan values with the isnan
function:
A = [1 NaN 3];
A(~isnan(A))
1 3
This actually removes nan values, however this is not always possible, e.g.
A = [1 nan; 2 3];
A(~isnan(A))
1
2
3
as you can see this destroys the matrix structure. You can avoid this by preallocating first and thereby setting the nan values to zero:
B = zeros(size(A));
B(~isnan(A))=A(~isnan(A))
B =
1 0
2 3
or, overwriting our original matrix A
A(isnan(A))=0
A =
1 0
2 3
回答2:
There are several functions that work with NaNs
: isnan
, nanmean
, max()
and min()
also have a NaN flag ('omitnan'
) whether you want to include NaNs in the min or max evaluation.
Although you must pay attention: sometimes the NaNs
can be as well generated by your code (e.g. 0/0 or also when performing standardization (x-mean(x))/std(x)
if x
contains either 1 value or several but equal values).
回答3:
You cannot avoid NaN
since some computations produces it as a result. For example, if you compute 1/0-1/0
you will get NaN
. You should deal with NaN
s in the code level, using builtin functions like isnan
.
回答4:
Several situations that come up with a matrix A
containing NaN values:
(1) Construct a new matrix where all rows with a NaN are removed.
row_mask = ~any(isnan(A),2);
A_nonans = A(row_mask,:);
(2) Construct a new matrix where all columns with a NaN are removed.
column_mask = ~any(isnan(A),1);
A_nonans = A(:, column_mask);
(3) Construct a new matrix where all NaN entries are replaced with 0.
A_nans_replaced = A;
A_nans_replaced(isnan(A_nans_replaced)) = 0;
回答5:
Easy:
A=[1 2; nan 4];
A(isnan(A))=0;