How to pick two values along a noisy amplitude spectrum that correspond to a specific value?

1 次查看(过去 30 天)
I am trying to pick two values along a amplitude spectrum (P1 vector) that are approximately equal to half the maximum amplitude of the spectrum and then find the indexes of those values. But my code only picks one value on the right side of the spectrum for both picks and it is not along the spectrum (green dot but is now in a different position than is shown in image below). There are two peaks in this dataset and I want to be able to repeat this for the second peak. What is causing this issue in my code below and what do I change it to to fix this problem?
halfAmp = maxAmp/2; % estimate what the half the maximum amplitude is, maxAmp is outputted by another function
[val,idx]=min(abs(P1_Trim-halfAmp)); % determine index and value of num in P1 array that is closest to calculated halfAmp
closestVal=P1_Trim(idx); % halfAmp value in dataset that is closest to the calculated halfAmp
idx1 = find(P1_Trim==closestVal,1,'first') % find index of P1 corresponding to half the height of total amplitude on left side (first time value is encountered)
idx2 = find(P1_Trim==closestVal,1,'last')% find index of P1 corresponding to half the height of total amplitude on right side (last time value is encountered)
P1_idx1 = P1_Trim(idx1) % P1 value that corresponds to left side pick index
P1_idx2 = P1_Trim(idx2) % P1 value that corresponds to right side pick index
freq1 = f_Trim(idx1);
freq2 = f_Trim(idx2);
figure(1)
plot(f_Trim,P1_Trim,'k')
hold on
plot(freq,maxAmp,'.r','MarkerSize',10)
hold on
plot(freq1,P1_idx1,'.b','MarkerSize',10)
hold on
plot(freq2,P1_idx2,'.g','MarkerSize',10)
hold off
xlabel('f (Hz)')
ylabel('P1 (dB)')
xlim([400,700])

回答(1 个)

Brian
Brian 2022-11-21
Your search finds the closest point to your given value, but that point is outside of the plot window.
Instead, you could search both the left and right sides of the peak for your points. For example,
halfAmp = maxAmp/2; % estimate what the half the maximum amplitude is, maxAmp is outputted by another function
[~,lIdx] = min(abs(P1_Trim(1:8405)-halfAmp));
[~,rIdx] = min(abs(P1_Trim(8406:11451)-halfAmp));
rIdx = rIdx + 8405; % adjust for search window
figure(1)
plot(f_Trim,P1_Trim,'k')
hold on
plot(freq,maxAmp,'.r','MarkerSize',10)
plot(f_Trim(lIdx),P1_Trim(lIdx),'.b','MarkerSize',10)
plot(f_Trim(rIdx),P1_Trim(rIdx),'.g','MarkerSize',10)
hold off
xlabel('f (Hz)')
ylabel('P1 (dB)')
xlim([400,700])
I chose the bounds for the search by plotting with
>> plot3(f_Trim,P1_Trim,1:length(f_Trim));view(2);
then selecting the points I wanted to use and using their indices (Z values).

类别

Find more on Matrices and Arrays 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!

Translated by