You may be making this too difficult.
Example —
a = linspace(0, 4*pi);
y = sin(a);
[pks,pkloc] = findpeaks( y,a);
[vls,vlloc] = findpeaks(-y,a);
figure(1)
plot(a, y, '-b')
hold on
plot(pkloc, pks, '^r', 'MarkerFaceColor','r')
plot(vlloc, -vls, 'vg', 'MarkerFaceColor','g')
hold off
grid
axis([xlim -1.1 1.1])
legend('Data', 'Peaks', 'Valleys')
Note that to plot the valleys (‘vls’) or minima correctly, simply negate them in the plot call. So to find them, use:
[vls,vlloc] = findpeaks(-y,a);
and to plot them or use them in other calculations correctly, negate them again to restore their correct values:
plot(vlloc, -vls, 'vg', 'MarkerFaceColor','g')
Best Answer