How to find max value for a function between 2 specified values

203 ビュー (過去 30 日間)
Anthony Koning
Anthony Koning 2023 年 4 月 24 日
コメント済み: John D'Errico 2023 年 4 月 25 日
Hi, I'm wondering how the max function can be used to both find the maximum output value, the given input value that results in that output, and only to search within a specified range. For example, if I had a basic sin(x) function, and wanted to know the maximum output and what input results in that value (1 and pi/2 respectively), and to only look for input values between 0 and pi, how would the code be set up? I've been trying to use
a = max(y, [], [0 pi])
where y is my function of sin(x). But to no avail, which just results in listing every value of the function.

回答 (2 件)

Kevin Holly
Kevin Holly 2023 年 4 月 24 日
x = 0:0.1:2*pi;
y = sin(x);
plot(x,y)
[maxvalue,index] = max(y(1:length(0:0.1:pi)))
maxvalue = 0.9996
index = 17
x(index)
ans = 1.6000
  2 件のコメント
Anthony Koning
Anthony Koning 2023 年 4 月 24 日
Would there be any way to set this up without expliciltely defining the sine function as only 0 to pi? Like if I wanted to plot from x is 0-10, then the output would be max at pi/2 and 5pi/2?
John D'Errico
John D'Errico 2023 年 4 月 25 日
It is difficult to know where you are going with this. Can you automatically determine for some generic nonlinear function where ALL the maxima lie? Of course not.
Can you determine where the maxima lie for some general function? Sometimes. You could use the symbolic toolbox to locate the roots of the derivative function, then determine which of them are maxima, and which lie in that interval.
Or, you could evaluate the function at many points in the interval, since you want to plot it anyway, and then use a tool like findpeaks to find the local maxima in that interval.

サインインしてコメントする。


John D'Errico
John D'Errico 2023 年 4 月 24 日
編集済み: John D'Errico 2023 年 4 月 24 日
Use fminbnd.
fun = @(x) sin(x);
[xloc,fval] = fminbnd(@(x) -fun(x),0,pi);
xloc
maxval = -fval
So the maximum arises at x==pi/2, as expected.
I had to negate the function since fminbnd is a minimizer. Remember that fminbnd will only find one locally maximal value. It cannot insure the globally maximum value is found. To insure that could be difficult, since I can always cook up a function that will cause any such tool to fail.

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by