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.
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!