%% Fill with Previous Value Using Custom Function
% Define a custom function to fill NaN values with the previous nonmissing value.
% Define a vector of sample points t and a vector of corresponding data A containing NaN values. Plot the data.

t = 10:10:100;
A = [0.1 0.2 0.3 NaN NaN 0.6 0.7 NaN 0.9 1];
plot(t,A,'o')

% Use the local function forwardfill (defined at the end of the example) to fill missing gaps with the previous nonmissing value. The function handle inputs include:
% xs — data values used for filling
% ts — locations of the values used for filling relative to the sample points
% tq — locations of the missing values relative to the sample points
% n — number of values in the gap to fill

n = 2;
gapwindow = [10 0];

[F,TF] = fillmissing(A,@(xs,ts,tq) forwardfill(xs,ts,tq,n),gapwindow,'SamplePoints',t);

% The gap window value [10 0] tells fillmissing to consider one data point before a missing gap and no data points after a gap, since the previous nonmissing value is located 10 units prior to the gap. The function handle input values determined by fillmissing for the first gap are:
% xs = 0.3
% ts = 30
% tq = [40 50]
% The function handle input values for the second gap are:
% xs = 0.7
% ts = 70
% tq = 80
% Plot the original data and the filled data.

plot(t,A,'o',t(TF),F(TF),'ro')

%

function y = forwardfill(xs,ts,tq,n)
% Fill n values in the missing gap using the previous nonmissing value
y = NaN(1,numel(tq));
y(1:min(numel(tq),n)) = xs;
end

% Copyright 2020 The MathWorks, Inc.