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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by