Finding max value of a function in specific range

조회 수: 11 (최근 30일)
Alin Brad
Alin Brad 2018년 9월 29일
편집: jonas 2018년 9월 29일
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))

채택된 답변

jonas
jonas 2018년 9월 29일
편집: jonas 2018년 9월 29일
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
Alin Brad
Alin Brad 2018년 9월 29일
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 2018년 9월 29일
편집: jonas 2018년 9월 29일
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

댓글을 달려면 로그인하십시오.

추가 답변 (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