use 1-d interpolation to replace the nans in “price1” to fill the data gaps. in matlab

You can use MATLAB's built-in function interp1 to perform 1-D interpolation of data. You'll need to first identify the NaN values in price1 using the isnan function:

main.m
% sample data
time = 1:10;
price1 = [10 15 NaN 20 NaN 25 30 35 NaN 40];

% identify NaN values in price1
nanInd = isnan(price1);

% interpolate using neighboring values
price1(nanInd) = interp1(time(~nanInd), price1(~nanInd), time(nanInd));

disp(price1);
256 chars
12 lines

Output:

main.m
   10   15   17.5   20   22.5   25   30   35   37.5   40
57 chars
2 lines

In the interp1 function, we pass the following arguments:

  • time(~nanInd): non-NaN time values
  • price1(~nanInd): non-NaN price values
  • time(nanInd): time values where NaN occurred and we want to interpolate price

related categories

gistlibby LogSnag