Finding max value of a function in specific range

6 vues (au cours des 30 derniers jours)
Alin Brad
Alin Brad le 29 Sep 2018
Modifié(e) : jonas le 29 Sep 2018
Dear All, I wrote this code to find the max value of function y within the (-0.5,0.5) range of x, however, it returns a erroe message (Warning: Integer operands are required for colon operator when used as index Subscript indices must either be real positive integers or logicals.) It looks not possible to use negative or non-integer values as indices. How can find the max value within the required range. Thanks
f = -8:0.002:8;
y=(1./((f.^2)+1))-(1.5./((f+0.9).^2+1))-1.5./((f-0.9).^2+1);
yn=y./max(y);
[pks, locs] = findpeaks (yn(-0.5: 0.5))

Réponse acceptée

jonas
jonas le 29 Sep 2018
Modifié(e) : jonas le 29 Sep 2018
yn(-0.5: 0.5)
This line returns the values of yn of the index in the braces. Problem is that those are not valid indices, as they need to be integers. If you need to return the values of yn where f>-.5 and f>.5 then you can use logical indexing instead
yn(f>-0.5 & f<0.5)
If you look at the data in this range, then you see that it's a "negative peak", or valley. To find this type of peaks, you need to use the findpeaks function as follows:
[pks, locs] = findpeaks (-1.*yn(f>-0.5 & f<0.5));
to get the actual peak value, we need to multiply the peak values by -1 again
pks=pks.*-1;
In my opinion, the better way would be to use both arrays as input
[pks, fx] = findpeaks (-1.*yn,f)
You can then select the peaks of interest
pks(fx>-.5 & fx<.5).*-1
  9 commentaires
Alin Brad
Alin Brad le 29 Sep 2018
i used your code
f = -8:0.002:8;
y=(1./((f.^2)+1))-(1.5./((f+0.9).^2+1))-1.5./((f-0.9).^2+1);
yn=y./max(y);
[pks, fx] = findpeaks (-1.*yn,f)
pks(fx>-.5 & fx<.5).*-1
plot(f,yn)
jonas
jonas le 29 Sep 2018
Modifié(e) : jonas le 29 Sep 2018
Hmm, maybe you are using an older version of findpeaks.. Try this instead:
y = @(f) (1./((f.^2)+1))-(1.5./((f+0.9).^2+1))-1.5./((f-0.9).^2+1);
fx=-0.05:0.001:0.05;
[pks,id]=findpeaks(y(fx))
fval=fx(id)
This was written on my phone so there could be typo. If the peak is

Connectez-vous pour commenter.

Plus de réponses (0)

Community Treasure Hunt

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

Start Hunting!

Translated by