Skipping nan's for computation and starting the vector where first value appears

1 回表示 (過去 30 日間)
Philipp
Philipp 2015 年 6 月 5 日
コメント済み: Stephen23 2015 年 6 月 10 日
Dear Matlab users,
I have two vectors of the same length, but one which has some missing values at the beginning:
x1= [1; 3; 4; 6; 8; 1; 3];
x2= [nan; nan; 5; 3; 7; 4; 2; 6];
of these two vectors I take the first difference to get the growth rates:
dx1=diff(x1);
dx2=diff(x2);
In a next step I would transform these growth rates (... with a break in the mean test, which is not described here as it does not matter for the example at hand) and add them back to the initial series. I use the following loop:
T=length(x1);
for tt=2:T
x1(tt,1)=x1(tt-1,1)+dx1(tt-1,1);
x2(tt,1)=x2(tt-1,1)+dx2(tt-1,1);
end
While this works fine if the vector does not contain any NAN, such as for x1:
x1= [1; 3; 4; 6; 8; 1; 3];
my problem is that for x2 there now appears the following:
x2=[NaN; NaN; NaN; NaN; NaN; NaN; NaN; 6];
How can I transform the loop such that it detects for x2 that the first two elements are nan and yet starts at x2(3,1)? This might be a silly and simple question but I was not able to find an answer within a reasonable amount of time and would appreciate very much your support.
Best and many thanks, Philipp

回答 (2 件)

Stephen23
Stephen23 2015 年 6 月 5 日
編集済み: Stephen23 2015 年 6 月 6 日
The function isnan is used to identify NaN values. Even better would be to use isfinite, assuming that the NaN values only occur consecutively at the start of the vector:
idx = isfinite(x1);
x1 = x1(idx);
If the NaN values are non-consecutive, then you could locate the last one using find, something like this:
idy = [find(isnan(x1),1,'last'),1];
x1 = x1(idy(1):end);
Of course if you want both vectors to be of the same length then you need to apply this indexing to both of them.
Note that the for-loop can be replaced by much simpler and faster vectorized code:
x1 = x1(1)+cumsum([0;dx1])
x2 = x2(1)+cumsum([0;dx2])

Philipp
Philipp 2015 年 6 月 10 日
Thank you very much for your detailed answer which helped me a lot.
  1 件のコメント
Stephen23
Stephen23 2015 年 6 月 10 日
My pleasure!
Note that you should use the comment fields for commenting, as the Answer fields are really just for answering the question :)

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

カテゴリ

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