From: John D'Errico on 18 Jun 2010 05:15 "Stephanie " <stephanie.turnbull(a)strath.ac.uk> wrote in message <hut2io$mf8$1(a)fred.mathworks.com>... > Hi there, > > I have a vector where the first few values at the beginning and end are NaN, and I would like to replace these values with the nearest "real" value. > > For example; > > NaN > NaN > NaN > 3 > 6 > 10 > 30 > 100 > NaN > NaN > > Would become; > > 3 > 3 > 3 > 3 > 6 > 10 > 30 > 100 > 100 > 100 > > Also, could this be applied to a matrix with the same problem? E.g. the first few rows and the last few rows of a matrix all contain NaN to be filled with nearest non-NaN value? > > Many thanks, > Steph I'm surprised nobody responded to this when it was posted. Perhaps the issue is it is trivial to solve for a vector, but not so in two dimensions. Thus for a vector, you would simply find the first non-NaN element, and replace everything before it with that number. Do the same with the last non-NaN element. That rule fails for an array however. Or what if you have NaNs inside the vector? Again, this becomes more difficult. Will you try to interpolate then? A scheme that will do reasonably well, with a smooth interpolant in one or two dimensions is inpaint_nans, using its method 4. Its a bit overkill, but it works. X0 = [nan; nan; nan; 3; 6; 10; 30; 100; nan; nan]; X1 = inpaint_nans(X0,4); [X0,X1] ans = NaN 3 NaN 3 NaN 3 3 3 6 6 10 10 30 30 100 100 NaN 100 NaN 100 Find inpaint_nans on the file exchange. http://www.mathworks.com/matlabcentral/fileexchange/4551 HTH, John
|
Pages: 1 Prev: Convert number to date Next: Interpolation- Negative values |