%% Identify Clipped Data in a Saturated Signal
% Sensors can return "clipped" readings if the data are larger than a given saturation point. The function findpeaks can find these flat peaks.
% Take for example a sensor that measures the displacement of a building floor during an earthquake. Read the CSV data using load. The first column is the time, measured in seconds. The second column is the displacement of the floor in centimeters. Plot it. The central portion of the data has many flat peaks, indicating sensor saturation.

load tremor.csv

time = tremor(:,1);
disp = tremor(:,2);

plot(time,disp)
xlabel('Time (s)')
ylabel('Drift (cm)')
title('Saturated')

%
% Use findpeaks, with the adjustable parameter 'threshold', to find the data to keep. With this option, a point is considered a peak if it is 'threshold' higher than its neighbors.

tolx = 1e-5;

[pkmaxt,locmaxt] = findpeaks(disp,'threshold',tolx);
[pkmint,locmint] = findpeaks(-disp,'threshold',tolx);

plot(time,disp,'-',time(locmaxt),pkmaxt,'o',time(locmint),-pkmint,'o')
xlabel('Time (s)')
ylabel('Drift (cm)')
title('Thresholded')

%
% Save the non-saturated portions of the signal as separate variables.

[mx,lmx] = max(diff(locmaxt));
[mn,lmn] = max(diff(locmint));

cutlft = max(locmaxt(lmx),locmint(lmn));
cutrgt = min(locmaxt(lmx+1),locmint(lmn+1));

timesm = time(1:cutlft);
timelg = time(cutrgt:end);
dispsm = disp(1:cutlft);
displg = disp(cutrgt:end);

subplot(1,2,1)
plot(timesm,dispsm)
xlabel('Time (s)')
ylabel('Drift (cm)')
title('Before Saturated Region')

subplot(1,2,2)
plot(timelg,displg)
xlabel('Time (s)')
ylabel('Drift (cm)')
title('After Saturated Region')

% Copyright 2015 The MathWorks, Inc.