MATLAB: Critical points of a polynomial function

polynomial

Hi everybody,
I would like to know the Matlab code to obtain the value of x at the maximum "y" value for a 3rd order polynomial. Basically, I have to obtain the area under the curve of a plot by integrating from 0 to the "x" value at the maximum "y" point.
I will appreciate any suggestion,
Thanks
Sergio

Best Answer

Does something like this work:
x_range = [0,10];
p = [1,4,-2,1]; % the 3rd order polynomial coefficients for (x^3+4*x^2-2*x+1)
k = polyder(p); % find derivative of above polynomial
r = roots(k); % find roots of polynomial created from derivative above
r = r(r>=x_range(1)); % get rid of roots less than x_min
if ~isempty(r)
r = r(r<=x_range(2)); % get rid of roots greater than x_max
end
if ~isempty(r)
try_points = zeros(1,2+length(r)); % pre-allocate
try_points(1:2) = x_range; % add x_min and x_max to list to try
for ii = 1 : length(r)
try_points(2+ii) = r(ii);
end
else
try_points = x_range;
end
y = polyval(p,try_points);
[max_y,xi] = max(y);
peak_at_xy = [try_points(xi),max_y]; % x & y coordinates of peak
This program basically takes the derivative of your polynomial (coefficients defined in "p") to find the peaks a valleys, then it compiles a list of "x" values inside your range in "x" (i.e., "x_range"). It then computes y for that list of "x" values to try and finds the "x" that gives the maximum "y" on the interval defined by "x_range". Of course, you would define the maximum "x" in "x_range" to be whatever you want.
Related Question