我试图在一组数据中找到连续的NAN,并在不干扰我已经填写的NAN的情况下,用最接近的已知数据点填写缺失的NAN。到目前为止,我为这个函数编写的代码是:
function [max_x, min_x] = missing(x)
max_x = x(:, 2);
min_x = x(:, 3);
for jj = 1:length(max_x)
for kk = 1:length(min_x)
if isnan (max_x(jj))
max_x (jj) = ((max_x(jj-1)+max_x(jj+1))/2);
elseif isnan (min_x(kk))
min_x (kk) = ((min_x(kk-1)+min_x(kk+1))/2);
elseif isnan (max_x(jj)>1)
max_x = fillmissing (max_x,'nearest');
end
end
end
这将填充单个NAN。如何填写其他缺失的连续NAN?
试试这个
x = [ nan 1 nan 2 nan nan 3 nan 4 nan nan 5 nan ];
% Handle outer nan's special way, just first & last not nan's
in = find(isnan(x));
nnF = find(~isnan(x), 1, 'first');
nnL = find(~isnan(x), 1, 'last');
x( in( in < nnF ) ) = x( nnF );
x( in( in > nnL ) ) = x( nnL );
% Now handle inner nan's
in = find(isnan(x));
nn = find(~isnan(x));
% Find close low & high neighbors
low = interp1( nn , nn , in , 'previous' );
high = interp1( nn , nn , in , 'next' );
% Is it closer to low, high, or equal from both
closerToLow = in - low < high - in;
equidistance = in - low == high - in;
closerToHigh = in - low > high - in;
% Perform transform
x(in(closerToLow)) = x(low(closerToLow));
x(in(equidistance)) = (x(low(equidistance)) + x(high(equidistance)))/2;
x(in(closerToHigh)) = x(high(closerToHigh));