Replacing NaN with the average of previous and next cell value

조회 수: 6 (최근 30일)
krai
krai 2018년 6월 7일
댓글: Jan 2018년 6월 8일
I have a data set like,
time 1 2 3 4 5 6 7 8
exp1 45 67 78 NaN 80 81 82 83
These are two separate column with time and exp1 as header. how do I replace the NaN with the average of previous cell value and the next. Like in the above example, NaN should be replaced by 79 ((78+80)/2 )
Thanks in advance
  댓글 수: 3
Jan
Jan 2018년 6월 7일
Please post the input data in valid Matlab syntax. A "data set" might be a variety of things.
Paolo
Paolo 2018년 6월 7일
Also, can there be multiple NaNs?

댓글을 달려면 로그인하십시오.

채택된 답변

Razvan Carbunescu
Razvan Carbunescu 2018년 6월 7일
This sounds like a use for fillmissing with linear option:
>> exp1 = [45 67 78 NaN 80 81 82 83];
>> fillmissing(exp1,'linear')
ans =
45 67 78 79 80 81 82 83
  댓글 수: 2
krai
krai 2018년 6월 8일
It works as required. Thanks
Jan
Jan 2018년 6월 8일
+1. Yes, fillmissing is better than fillgaps.

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Jan
Jan 2018년 6월 7일
편집: Jan 2018년 6월 7일
Maybe:
y = fillgaps(exp1, 3, 1)
% Needs Matlab >= R2016a
[EDITED] Sorry, this does not do, what I expect.
According to the documentation I'd expect a linear fit to the neighboring
elements.
Or:
valid = ~isnan(exp1);
y = exp1;
y(~valid) = interp1(time(valid), exp1(valid), time(~valid))
This is a linear interpolation.

Paolo
Paolo 2018년 6월 7일
편집: Paolo 2018년 6월 7일
If you are working with a table:
%Table.
var = {'time';'exp1'};
time = [1;2;3;4;5;6;7;8];
exp1 = [45;67;78;NaN;80;81;82;83];
t = table(time,exp1);
x = t.exp1;
nan = isnan(x);
indx = find(nan);
x(nan) = (x(indx-1)+x(indx+1))/2;
t.exp1 = x;
If you are working with a cell array:
%Cell array.
var = {'time',1,2,3,4,5,6,7,8;'exp1',45,67,78,NaN,80,81,82,83};
x = cell2mat(var(2,2:end));
nan = isnan(x);
indx = find(nan);
x(nan) = (x(indx-1)+x(indx+1))/2;
var(2,2:end) = num2cell(x);

카테고리

Help CenterFile Exchange에서 Data Preprocessing에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by