MATLAB: How to fill data gaps in a time series with NaN

data gapsnan

Dear All,
I am having a time series with some gaps in it and i want to fill the gaps with NaN, how can I do that the…..the interval of my time series is 0.00274

Best Answer

I am not certain what you want to do, but if you want to create a continuous time vector and fill the corresponding missing data values with NaN, this works:
Ts = 0.00274; % Sampling Time
t = [0:10 14:20 25:30]*0.00274; % Create Time Series With Gaps
f = rand(size(t)); % Create Matching Data
tn = round(t/Ts); % Create Indices With Gaps
dt = diff([0 tn]); % Create Vector Of Differences
tg = find(dt > 1); % Find Indices Of Gaps
gaps = dt(tg)-1; % Find Lengths Of Gaps
ti = linspace(min(t),max(t),max(tn)); % Create Continuous Time Vector
fi = interp1(t,f,ti); % Create Matching Data Vector
for k1 = 1:length(tg) % Loop Filling Gaps In ‘f’ With NaN
q = [tg(k1):tg(k1)+gaps(k1)-1];
fi(tg(k1):tg(k1)+gaps(k1)-2) = nan(1,gaps(k1)-1);
end
If you also want the time vector to have NaN values (not recommended), add this line after the ‘fi’ assignment in the loop:
ti(tg(k1):tg(k1)+gaps(k1)-1) = nan(1,gaps(k1));
The output of this routine are the time vector ‘ti’ and the data vector ‘fi’.
There are likely different ways to do this. This method seems to do what you want.