필터 지우기
필터 지우기

findpeaks function adds nan at the beginning and end

조회 수: 3 (최근 30일)
Lok Yiu To
Lok Yiu To 2018년 7월 17일
댓글: Lok Yiu To 2018년 7월 17일
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;

채택된 답변

Walter Roberson
Walter Roberson 2018년 7월 17일
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Descriptive Statistics에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by