我想将[1 nan 1 2 2 nan nan 3 nan 4 nan nan 5]
更改为[1 1.5 1 2 2 2 3 3 3.5 4 4 5 5]
。如果有一个NAN,我希望在NAN中填写前后数字的平均值。如果存在多个NAN。我想用最接近的数字填写NAN。
到目前为止,我只有找到单个NAN的代码:
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);
end
end
end
如何填写非单一NAN?
非常感谢。
这个问题的标题几乎就是答案-使用fillmissing
填充缺失的值。
A = [1 nan 1 2 2 nan nan 3 nan 4 nan nan 5];
B = fillmissing(A,'linear');
此功能在R2016b中引入。
使用interp1
和isnan
可以实现相同的逻辑。
idx = ~isnan( A );
x = 1:numel(A);
B = interp1( x(idx), A(idx), x, 'linear', 'extrap' );
注意,这里的外推对于输入向量的每一端的NaN
值给出了略微不同的行为。
示例代码:
% To paste in main .m file
A = [1 nan 1 2 2 nan nan 3 nan 4 nan nan 5]; % Input array
[A] = new_array(A) % Function to get a new array
% To paste in individual .m file as function
function [x]= new_array(x)
is_nan_ar = isnan(x); % Getting 0/1 array of nan elements
array_l = length(x); % Getting length of x array (just to do it only once)
for k = 1:array_l % Checking every element of input array whether it's...
if (k==1) && (is_nan_ar(k)==1) % First element and nan
kk = 2; % Initial index for searching the nearest non-nan element
while (isnan(is_nan_ar(kk))==1) % Checking elements for being nan
kk=kk+1; % Increasing index while we're searching
end
x(k) = x(kk); % Writing down the first not nan element
elseif (k==array_l) && (is_nan_ar(k)==1) % The same search for the last
kk = array_l-1; % Intial index
while (isnan(is_nan_ar(kk))==1) % Reversed search for not not nan
kk=kk-1;
end
x(k) = x(kk); % Writing down what we found
elseif (is_nan_ar(k)==1) % When we're checking not the first and not the last
s_r = 1; % Search range (1 element to the left/right)
while (is_nan_ar(k-s_r)==1) && (is_nan_ar(k+s_r)==1) %Looking for not nan
s_r = s_r+1; % Increasment of the range if didn't find
end
if (is_nan_ar(k-s_r)==0) && (is_nan_ar(k+s_r)==0) % Two non-nans are near
x(k) = (x(k-s_r)+x(k+s_r))/2;
elseif (is_nan_ar(k-s_r)==0) % Only one non-nan on the left
x(k) = x(k-s_r);
else % Only one non-nan on the right
x(k) = x(k+s_r);
end
end
end
end