From: Jos (10584) on
"Stephanie " <stephanie.turnbull(a)strath.ac.uk> wrote in message <hut2q8$7pk$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

Here is one approach:

m = [NaN NaN 1 2 3 NaN NaN NaN].' % data
q = ~isnan(m)
ix = find(q,1,'first')
m(1:ix-1) = m(ix)
ix = find(q,1,'last')
m(ix+1:end) = m(ix)

For matrices, you can use a for-loop over columns.

hth
Jos