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

211 次查看(过去 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.

回答(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 CenterFile Exchange 中查找有关 MATLAB 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by