MATLAB: How to select a specific peak in a repeating pattern

findpeakspeakpeak analysispeaksSignal Processing Toolboxspecific peak

y is my data and I am trying to find the first peak of each repeating part, but in the third part, the last peak is greater than the first peak so the last peak is the peak that gets selected. This problem only occurs when the last peak is greater than the first peak. Nothing I have tried has been working.
pks = findpeaks(y,'MinPeakHeight', 200,'MinPeakDistance',4000)

Best Answer

Try this:
clc; % Clear command window.
clear; % Delete all variables.
close all; % Close all figure windows except those created by imtool.
workspace; % Make sure the workspace panel is showing.
fontSize = 24;
s = load('dataa.mat')
z = s.z;
plot(z, 'b-', 'LineWidth', 2);
grid on;
hold on;
title('z vs. Index', 'FontSize', fontSize);
xlabel('Index', 'FontSize', fontSize);
ylabel('z', 'FontSize', fontSize);
% Label different squarish regions.
[labeledSignal, numRegions] = bwlabel(z > 200);
% Find indexes of each group
props = regionprops(labeledSignal, 'PixelIdxList');
% Examine each group to find out where the signal decreases
for k = 1 : numRegions
% Get indexes of only this group.
theseIndexes = props(k).PixelIdxList;
% Plot a red line where the group starts.
line([theseIndexes(1), theseIndexes(1)], ylim, 'Color', 'r', 'LineWidth', 2);
% Get differences. If it's going up, differences will be positive.
% When it turns around, the difference values will be zero or negative.
diffs = diff(z(theseIndexes));
% Find out where diffs <= 0
peakIndex(k) = find(diffs <= 0, 1, 'first') + theseIndexes(1) - 1;
% Tell user what the index is.
fprintf('The peak for group #%d is at index %d.\n', k, peakIndex(k));
% Plot a magenta line where the first peak in the group is.
line([peakIndex(k), peakIndex(k)], ylim, 'Color', 'm', 'LineWidth', 2);
end
%------------------------------------------------------------------------------
% Set up figure properties:
% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]);
% Get rid of tool bar and pulldown menus that are along top of figure.
% set(gcf, 'Toolbar', 'none', 'Menu', 'none');
% Give a name to the title bar.
set(gcf, 'Name', 'Demo by ImageAnalyst', 'NumberTitle', 'Off')
Each group starts at the red line, and the very first peak has its highest point at the magenta line.