Interpolation of nan values

2 views (last 30 days)
Nicole Scerri
Nicole Scerri on 25 May 2015
Answered: Walter Roberson on 25 May 2015
I have a column with some Nans, and I'd like to interpolate the data to put numbers instead of the missing values.
The nans are in column 2.
Column 3 is the flag, so I'm looking for values that are number 4(flagged as missing/nan) and changing them to a 1(flagged as changed interpolated data), after the change is done.
This is what I tried:
numRows = size(database,1);
for i=1:numRows
if database(i,3) == 4;
database(i,2) = interp1(database(i,2),'linear')
database(i,3) = 1;
end
  1 Comment
Stephen23
Stephen23 on 25 May 2015
Edited: Stephen23 on 25 May 2015
Do not use i or j for variable names, as these are both names of the inbuilt imaginary unit.

Sign in to comment.

Answers (2)

Stephen23
Stephen23 on 25 May 2015
Edited: Stephen23 on 25 May 2015
Here is an example of how to achieve something like what you need:
>> B(:,2) = [1,2,NaN,4,NaN,6,7,NaN,9];
>> B(:,3) = [0,0, 4,0, 4,0 0, 4,0]
B =
0 1 0
0 2 0
0 NaN 4
0 4 0
0 NaN 4
0 6 0
0 7 0
0 NaN 4
0 9 0
>> idx = B(:,3)==4;
>> B(idx,2) = interp1(find(~idx), B(~idx,2), find(idx));
>> B(idx,3) = 1
B =
0 1 0
0 2 0
0 3 1
0 4 0
0 5 1
0 6 0
0 7 0
0 8 1
0 9 0
Note that this completely avoids using any loop at all (i.e. fully vectorized code), and that it uses a syntax that taken from the interp documentation.

Walter Roberson
Walter Roberson on 25 May 2015
Get John D'Errico's inpaint_nans

Community Treasure Hunt

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

Start Hunting!