%% Plot the Conditional Temporal Moments of a Time Series Vector
% Plot the conditional temporal moments of a time series using a plot-only approach and a return-data approach.
%
% Load and plot the data, which consists of simulated vibration measurements for a system with a fault that causes periodic resonances. x is the vector of measurements, and fs is the sampling frequency.

load tftmoment_example x fs

ts=0:1/fs:(length(x)-1)/fs;
figure
subplot(1,2,1)
plot(ts,x)
xlabel('Time in Seconds')
ylabel('Measurement')
title('Simulated Vibration Measurements')

% Use the function pspectrum with the 'spectrogram' option to show the frequency content versus time.

subplot(1,2,2)
pspectrum(x,ts,'spectrogram')

% The spectrogram shows that the first burst is at 100 Hz, and the second burst is at 300 Hz.  The 300-Hz burst is stronger than the 100-Hz burst by 70 dB.
%
% Plot the second temporal moment (variance), using the plot-only approach with no output arguments and specifying fs.

figure
order = 2;
tftmoment(x,fs,order);title('Second Temporal Moment')

% There are two distinct features in the plot at 100 and 300 Hz corresponding to the induced resonances shown by the spectrogram.  The moments  are much closer in magnitude than the spectral results were.
% Now find the first four temporal moments, using the timeline ts that you already constructed.  This time, use the form that returns both the moment vectors and the associated frequency vectors.  Embed the order array as part of the input argument.

[momentT,f] = tftmoment(x,ts,[1 2 3 4]);

% Each column of momentT contains the moment corresponding to one of the input orders.

momentT_1 = momentT(:,1);
momentT_2 = momentT(:,2);
momentT_3 = momentT(:,3);
momentT_4 = momentT(:,4);

% Plot the four moments separately to compare the shapes.

figure
subplot(2,2,1)
plot(f,momentT_1)
title('First Temporal Moment — Mean')
xlabel('Frequency in Hz')

subplot(2,2,2)
plot(f,momentT_2)
title('Second Temporal Moment — Variance')
xlabel('Frequency in Hz')

subplot(2,2,3)
plot(f,momentT_3)
title('Third Temporal Moment — Skewness')
xlabel('Frequency in Hz')

subplot(2,2,4)
plot(f,momentT_4)
title('Fourth Temporal Moment — Kurtosis')
xlabel('Frequency in Hz')

% For the data in this example, the second and fourth temporal moments show the clearest features for the faulty resonance.
% Copyright 2018 The MathWorks, Inc.