Site logo MA251: Calculus I
Fall 2007
MA251
Readings
Problems
Matlab
Locating a local max or min is a very simple task if you have Matlab! Suppose you have the function
f(x) = 2x6 + 3x5 +3x3-2x2
and you want to find the local max and mins. One method to do this is to graph the function and approximate the max/mins by viewing the graph and zooming. An easier method is to take advantage of Matlab's commands fminsearch and fminbnd. To do this we first create a variable to hold the function:

>> y = @(x)2*x.^6+3*x.^5+3*x.^3-2*x.^2;

Then we can graph the function using our normal linspace and plot commands:

>> X = linspace(-10,10);
>> plot(X,y(X))

It is very difficult to see where the minimum is so we zoom in:
>> X = linspace(-3,2);
>> plot(X,y(X))

We can find the exact value for the min using one of two methods. The first is to use fminsearch:

>> [xmin,ymin]=fminsearch(y,-2)

This says to start looking around -2 for the min. Another method is to use fminbnd:

>> [xmin,ymin]=fminbnd(y,-2,-1)

This method says to search for the minimum in the area between -2 and -1. Note that you can use fminsearch and fminbnd to also look for max. This can be calculated by looking at the negative of the function. Therefore, max becomes min.
Another method is to look at the roots of the first derivative. This can be attained easily in matlab by typing the following commands:

>> syms x
>> dy = diff(2*x.^6+3*x.^5+3*x.^3-2*x.^2)

dy =
12*x^5+15*x^4+9*x^2-4*x
>> roots([12 15 0 9 -4 0])

ans =
0
-1.6161
0.0073 + 0.7659i
0.0073 - 0.7659i
0.3516

We see that we missed two other critical points. One at 0 and one at approximately 0.3516. Zoom in to the original function and determine if these were max or mins. Another tip to help you plot derivatives is to use the command subs. This will substitute the symbolic variable for the number x you want to use. For example,

>> syms x
>> dy = diff(2*x.^6+3*x.^5+3*x.^3-2*x.^2);
>> X = linspace(-10,10);
>> plot(X,subs(dy,x,X))