how to put range for findpeaks function
13 views (last 30 days)
Show older comments
Omer hakan Yaran
on 28 Jun 2022
Answered: Pratyush Swain
on 29 Jun 2022
I have a frequency data from 0 Hz to 5 Hz but I want to find peaks only in between 0.2 Hz and 5 Hz. I have seen some people using the method below:
[pks,locs] = findpeaks(data(0:135))
But the problem is I am using two different vectors, one for the magnitute of the frequency and the other for the corresponding frequency. For example
0.0100 12.567
this row means a data point with 0.0100 Hz frequency and 12.567 magnitute. So I don't know the indices of 0.2 Hz or 5 Hz to put a range.
0 Comments
Accepted Answer
Star Strider
on 28 Jun 2022
One approach
f = linspace(0, 25, 250).'; % Frequency Vector
data = exp(-0.1*f) .* sin(2*pi*f*120); % Amplitude Vector
[pks,locs] = findpeaks(data);
DesiredVals = f(locs) >=0 & f(locs)<=5;
DesiredLocs = locs(DesiredVals);
Results = table(f(DesiredLocs), data(DesiredLocs), 'VariableNames',{'Frequency','Amplitude'})
figure
plot(f, data)
hold on
plot(f(DesiredLocs), data(DesiredLocs), '^r')
hold off
grid
xlabel('Frequency')
ylabel('Amplitude')
Experiment with your data.
.
0 Comments
More Answers (1)
Pratyush Swain
on 29 Jun 2022
Hey,
As you have two vectors for frequency and magntude,you can use sorting vectors by same order,mentioned here -- sorting and also filter the indexes as per the given range requirement.
Note here findpeaks function expects the X-value(the frequency vector) to be strictly increasing hence the sorting needs to be carried out. Also the order of the steps involved here can be interchanged that is first the vectors can be filtered as per required range then sorted and vice-versa.
%taking an example frequency and magnitude array%
frequencies=[0.0 0.9 1.2 0.5 0.2 4.9 0.1];
magnitudes=[2 4 5 6 1 2 8];
%sort by order the frequencies and magnitudes%
[freqsorted,I] = sort(frequencies);
magnitudes = magnitudes(I);
%selected the indexes containing desired range of freq%
selected_freq_indexes=freqsorted>=0.2;
%now using the selected indexes obtain the final filtered freq array%
freqsorted=freqsorted(selected_freq_indexes);
%similary filter out the magnitude array%
magnitudes=magnitudes(selected_freq_indexes);
%finally filter out the peaks and their respective frequencies%
[pks,locs] = findpeaks(magnitudes,freqsorted)
Here we can take a look how the frequencies and magnitudes vector are ordered and filtered.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1049595/image.png)
Result after calling findpeaks function by passing in the magnitudes and freqsorted vectors as input arguments.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1049600/image.png)
Hope this helps.
0 Comments
See Also
Categories
Find more on Spectral Estimation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!