Skipping nan's for computation and starting the vector where first value appears
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (2)
Stephen23
on 5 Jun 2015
Edited: Stephen23
on 6 Jun 2015
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.
x1 = x1(1)+cumsum([0;dx1])
x2 = x2(1)+cumsum([0;dx2])
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!