How to find max value for a function between 2 specified values
203 ビュー (過去 30 日間)
古いコメントを表示
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.
0 件のコメント
回答 (2 件)
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)))
x(index)
2 件のコメント
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
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.
0 件のコメント
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!