Dealing with NaN's in matlab functions

独自空忆成欢 提交于 2019-11-28 14:08:14

You could do something like mean(x(~isnan(x))). If you want you could also write a bunch of wrappers like this and put them in your startup.m file.

As of MATLAB 2015a, mean supports an extra parameter, nanflag. Using the example from JoErNanO's answer,

A = [1 0 NaN; 0 3 4; 0 NaN 2];
mean(A, 'omitnan')
% = [0.333333333333333 1.5 3]

The default for that parameter is includenan, which will return NaN for columns/rows containing NaNs.

median, cov, min, max, sum, var and std also support ignoring of NaNs.

I think this should work:

mean(x(isfinite(x)));

What about Matrices?

As Karthik V suggests,

mean(x(~isnan(x)))

will work for vectors. However in case you have an n-by-m matrix and wish to compute the row-/column-wise mean discarding occasional NaN's you will have to run a for loop.

Sample Scenario

Imagine a data matrix of the form:

A = [1 0 NaN; 0 3 4; 0 NaN 2]

A =
 1     0   NaN
 0     3     4
 0   NaN     2

Running mean(A(~isnan(A))) yields:

ans =

1.4286

This is because the logical indexing effectively "flattens" the matrix into a vector.

Looping Solution (Column-wise Mean)

Assuming you want to compute the column-wise mean, the looping solution then becomes:

% Preallocate resulting mean vector
nCols = size(A, 2);
mu = zeros(1, nCols);

% Compute means
for col = 1:nCols
    mu(col) = mean(A(~isnan(A(:, col)), col));
end

Resulting in:

mu =

0.3333    1.5000    3.0000

Looping Solution (Row-wise Mean)

Assuming you want to compute the row-wise mean, the looping solution then becomes:

% Preallocate resulting mean vector
nRows = size(A, 1);
mu = zeros(nRows, 1);

% Compute means
for row = 1:nRows
    mu(row) = mean(A(row, ~isnan(A(row, :))));
end

Resulting in:

mu =

0.5000
2.3333
1.0000
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!