Replace Nan with previous numbers

6 ビュー (過去 30 日間)
aggelos
aggelos 2012 年 7 月 5 日
回答済み: Chad Greene 2014 年 11 月 1 日
Hello there , I have a Variable of type double with natural gas Prices that contains Nans for dates that I don't have data and i want to replace Nans with the previous day known price. I tried function "fillts" but i didn't got what I wanted to . I appreciate any help Thanks in advance
data = [...
7.51
NaN
NaN
7.61
NaN
NaN
7.85];

採用された回答

Andrei Bobrov
Andrei Bobrov 2012 年 7 月 5 日
編集済み: Andrei Bobrov 2012 年 7 月 5 日
t = ~isnan(data);
a = data(t);
out = a(cumsum(t));
ADD on Aggelos's comment
t = ~isnan(data);
idx = cumsum(t);
idx(~idx) = 1;
a = data(t);
out = a(idx);
  2 件のコメント
aggelos
aggelos 2012 年 7 月 5 日
Thanks very much Andrei ,but i get the following error...
>> t = ~isnan(NEdata.NaturalGas); a = NEdata.NaturalGas(t); out = a(cumsum(t)); Subscript indices must either be real positive integers or logicals.
aggelos
aggelos 2012 年 7 月 7 日
Thank you very much Andrei ... it works just fine . Thanks again ...keep on the great job

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

その他の回答 (3 件)

Image Analyst
Image Analyst 2012 年 7 月 5 日
Try this:
m = [nan 2 3 4 nan 6 7 nan 9] % Sample data
indexes = find(isnan(m))
if ~isempty(indexes)
% Handle case where first index is nan - get rid of it.
if indexes(1) == 1
m = m(2:end);
indexes = indexes(2:end) - 1
end
% Take prior index if element is nan.
m(indexes) = m(indexes-1)
end
  2 件のコメント
aggelos
aggelos 2012 年 7 月 5 日
I get the same error as with Andrei's answer :Subscript indices must either be real positive integers or logicals. Any suggestions... Thank you very much
Image Analyst
Image Analyst 2012 年 7 月 5 日
編集済み: Image Analyst 2012 年 7 月 5 日
You did something wrong, because I just copied and pasted my code on another computer and it worked great here also.
Plus you still need to say what you want done in case the first element is a nan. andrei and my vectorized solutions chose to handle it in different ways, while John non-vectorized code assumed that you would never have such a case (a non-robust, risky assumption). andrei's code seems to be even more robust than mine because his handles sequences of multiple nans in a row while mine doesn't. But his takes the second element for the first output element if the first input element is a nan, while mine just throws it away and shortens the array - that's why I asked what you want to do in such a case.

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


John
John 2012 年 7 月 5 日
try the following:
x = isnan(data);
for i = length(data)
if x(i) == 1
data(i) = data(i-1);
end
end

Chad Greene
Chad Greene 2014 年 11 月 1 日
repnan can do it by
data = repnan(data,'previous');

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by