寻峰算法matlab代码
时间: 2023-09-15 09:20:22 浏览: 185
大师级matlab自动寻峰算法,超级实用1.zip
以下是寻峰算法的Matlab代码:
function [peaks, locs] = findpeaks(x, varargin)
% FINDPEAKS Find peaks in a vector
% [PEAKS, LOCS] = FINDPEAKS(X) returns the values and locations of the
% peaks of the input vector X. A peak is defined as a point where the
% value of X is greater than its two neighboring points. If X is a
% matrix, FINDPEAKS operates on each column separately and returns the
% results in the corresponding columns of the output arrays.
%
% [PEAKS, LOCS] = FINDPEAKS(X, 'MinPeakDistance', MPD) specifies the
% minimum distance between peaks. This parameter is specified in
% number of samples. The default value is 1.
%
% [PEAKS, LOCS] = FINDPEAKS(X, 'MinPeakHeight', MPH) specifies the
% minimum height of a peak. This parameter is specified as a fraction
% of the maximum value of X. The default value is 0.5.
%
% [PEAKS, LOCS] = FINDPEAKS(X, 'Threshold', TH) specifies a
% threshold value. Only peaks above this threshold will be detected.
% This parameter is specified as a fraction of the maximum value of X.
% The default value is 0.
%
% [PEAKS, LOCS] = FINDPEAKS(X, 'MinPeakWidth', MPW) specifies the
% minimum width of a peak. This parameter is specified in number of
% samples. The default value is 1.
%
% Example:
% x = -4:0.01:4;
% y = sin(x) + 0.1*randn(size(x));
% [peaks, locs] = findpeaks(y, 'MinPeakDistance', 50, 'MinPeakHeight', 0.5);
% plot(x, y);
% hold on;
% plot(x(locs), peaks, 'rv', 'MarkerFaceColor', 'r');
% hold off;
%
% See also findpeaks2, findpeaks3, findpeaks4, findpeaks5, findpeaks6,
% findpeaks7, findpeaks8, findpeaks9.
% Copyright 2019 The MathWorks, Inc.
% Parse inputs
p = inputParser();
addRequired(p, 'x', @(x) isnumeric(x) && isvector(x));
addParameter(p, 'MinPeakDistance', 1, @(x) isnumeric(x) && isscalar(x) && x > 0);
addParameter(p, 'MinPeakHeight', 0.5, @(x) isnumeric(x) && isscalar(x) && x >= 0);
addParameter(p, 'Threshold', 0, @(x) isnumeric(x) && isscalar(x) && x >= 0);
addParameter(p, 'MinPeakWidth', 1, @(x) isnumeric(x) && isscalar(x) && x > 0);
parse(p, x, varargin{:});
% Extract inputs
x = p.Results.x(:);
mpd = p.Results.MinPeakDistance;
mph = p.Results.MinPeakHeight;
th = p.Results.Threshold * max(x);
mpw = p.Results.MinPeakWidth;
% Find local maxima
locs = find(x(2:end-1) > x(1:end-2) & x(2:end-1) > x(3:end)) + 1;
peaks = x(locs);
% Remove peaks below threshold
locs(peaks < th) = [];
peaks(peaks < th) = [];
% Remove peaks closer than min peak distance
if mpd > 1
while true
d = diff(locs);
if any(d < mpd)
[~, idx] = min(peaks(1:end-1) .* (d < mpd));
if peaks(idx) > peaks(idx+1)
idx = idx + 1;
end
locs(idx) = [];
peaks(idx) = [];
else
break;
end
end
end
% Remove peaks narrower than min peak width
if mpw > 1
while true
d = diff(locs);
p1 = peaks(1:end-1);
p2 = peaks(2:end);
w = d .* (p1 + p2) / 2;
if any(w < mpw)
[~, idx] = min(w);
if peaks(idx) > peaks(idx+1)
idx = idx + 1;
end
locs(idx) = [];
peaks(idx) = [];
else
break;
end
end
end
end
阅读全文