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

194 views (last 30 days)
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.

Answers (2)

Kevin Holly
Kevin Holly on 24 Apr 2023
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 Comments
Anthony Koning
Anthony Koning on 24 Apr 2023
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 on 25 Apr 2023
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.

Sign in to comment.


John D'Errico
John D'Errico on 24 Apr 2023
Edited: John D'Errico on 24 Apr 2023
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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!