How to get a specified number of local maxima?

Illustration
Daniella - 2021-01-08T09:53:37+00:00
Question: How to get a specified number of local maxima?

I have a  signal and I only want the top two or three local maxima, I don't want the 5000 maxima that the findpeaks() function gives me. Is there a way to get this? Thanks.  

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

function[val,idx]=nthMaxima(P0,n)
%P0 is the array for searching maximus in there 
%n is the number of top maximus to find 
val=zeros(1,n); %defining array for reserving value of maximus
idx=zeros(1,n); %defining array for index of maximus 

for i=1:n
    [val(i),idx(i)]=max(P0);  %taking maximu value and indexing 
    P0(idx(i))=-Inf;          %replacing maxima index with -Inf to search for maxima again
end

%recovering the replaced maxima value 
for j=1:n
    P0(idx(j))=max(j);
end
%done!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
end
You can use this function. I used this for taking top 2 frequency spectra maxima. You can find the min with the same logic.
**Update:Replace max(j) with val(j) in the function


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!