findpeaks function adds nan at the beginning and end
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Lok Yiu To
le 17 Juil 2018
Commenté : Lok Yiu To
le 17 Juil 2018
Hi all,
I am reading the matlab code for MATLAB built-in function, findpeaks. I am confused why one of its function findLocalMaxima has to "bookend the array" by NaN.
function [iPk, iInflect] = findLocalMaxima(yTemp)
% bookend Y by NaN and make index vector
yTemp = [NaN; yTemp; NaN];
iTemp = (1:numel(yTemp)).';
% keep only the first of any adjacent pairs of equal values (including NaN).
yFinite = ~isnan(yTemp);
iNeq = [1; 1 + find((yTemp(1:end-1) ~= yTemp(2:end)) & ...
(yFinite(1:end-1) | yFinite(2:end)))];
iTemp = iTemp(iNeq);
% take the sign of the first sample derivative
s = sign(diff(yTemp(iTemp)));
% find local maxima
iMax = 1 + find(diff(s)<0);
% find all transitions from rising to falling or to NaN
iAny = 1 + find(s(1:end-1)~=s(2:end));
% index into the original index vector without the NaN bookend.
iInflect = iTemp(iAny)-1;
iPk = iTemp(iMax)-1;
0 commentaires
Réponse acceptée
Walter Roberson
le 17 Juil 2018
Generally speaking, putting fixed values around an array is a useful technique to avoid having to write special code for the situation where the value of interest might be at one end of the array or the other.
For example, if the task were to find the beginning and end of sequences of negative numbers, then it is easy enough to do a vectorized test for when the sign of the data goes from non-negative to negative to mark the beginning of a sequence, and from negative to non-negative to mark the end of a sequence. But if the buffer of data starts with a negative value, then the start of the buffer needs to be identified as the start of a block of negative values, even though there is no transition from non-negative to negative. You can either do the vectorized transition test without guard values and handle the endpoints separately, or you can put guard values on the ends to introduce an artificial transition to be vectorized in, like
temp = sign([0, data, 0]);
find(temp(1:end-1) >= 0 & temp(2:end) < 0) %to identify the start of a block of negatives without needing to put special tests for beginning of block
Plus de réponses (0)
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!