Replacing NaN values with average values of the nearest numbers?

9 ビュー (過去 30 日間)
Isaac
Isaac 2014 年 10 月 29 日
コメント済み: Dyuman Joshi 2023 年 12 月 13 日
Hi, I have a data set with blocks of NaN Values. Is there a command that can fill in missing values by using the average of the values on either side?
For example, in the data set:
2
3
5
7
NaN
NaN
12
Is there a way to get something like 8.66 and 10.33 for the NaN numbers?
Also, would this work if there were multiple columns?
Thanks, Isaac
  1 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 12 月 13 日
For newer versions, fillmissing (Introduced in R2016b) is a robust option -
nandata=[2;3;5;7;nan;nan;12];
fillmissing(nandata, 'linear')
ans = 7×1
2.0000 3.0000 5.0000 7.0000 8.6667 10.3333 12.0000

サインインしてコメントする。

回答 (2 件)

Michael Haderlein
Michael Haderlein 2014 年 10 月 29 日
Hi Isaac,
you can use interp1:
nandata=[2;3;5;7;nan;nan;12];
xdata=(1:length(data))';
data=interp1(xdata(~isnan(nandata)),nandata(~isnan(nandata)),xdata)
data =
2.0000
3.0000
5.0000
7.0000
8.6667
10.3333
12.0000
For multiple columns, you'll need bsxfun:
nandata2=[2 1;3 nan;5 2;7 nan;nan nan;nan 1;12 10];
xdata2=(1:size(nandata,1))';
data2=bsxfun(@(x,y) interp1(y(~isnan(x)),x(~isnan(x)),y),nandata2,xdata2)
data2 =
2.0000 1.0000
3.0000 1.5000
5.0000 2.0000
7.0000 1.6667
8.6667 1.3333
10.3333 1.0000
12.0000 10.0000
  1 件のコメント
Joshua Larkin
Joshua Larkin 2018 年 12 月 14 日
編集済み: Joshua Larkin 2018 年 12 月 14 日
Finally I found somthing that worked for what I needed. Thanks for the great answer!

サインインしてコメントする。


Chad Greene
Chad Greene 2014 年 11 月 4 日
With repnan,
nandata=[2;3;5;7;nan;nan;12];
data = repnan(nandata)
2.0000
3.0000
5.0000
7.0000
8.6667
10.3333
12.0000
  1 件のコメント
Ismet Handzic
Ismet Handzic 2020 年 4 月 10 日
hmmm.... only seems to work when there are bounded values, like that last 12 at the end there. But good suggestion!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by