max - Minimum and maximum values of a function with endpoints: MATLAB

I am trying to evaluate and find the minimum and maximum values of a function over a certain interval. I also want it to evaluate the endpoints to see if they are the maximum or the minimum values. I have the following code which is not giving me what I want. The minimum values should be -1 and 2 but I am getting -0.9999 and 1.9999. Any help would be much appreciated.

``minVal1 = fminbnd(f,-1,0);minVal2 = fminbnd(f,0,2);``

I believe that your problem lies in the fact that the default of `TolFun` for Matlab's fminbnd` function is 0.0001 - so when the function evaluation changes by less than that number, it stops. This may lead to stopping before reaching the true maximum.

If you want to be "right to within 0.0001", you need to set the tolerance on the function evaluation. You could use for example

``````minVal1 = fminbnd(f, -1, 0, optimset('TolFun', 1e-5));
``````

That ought to get you the precision you need. Make the tolerance even smaller if you need greater precision (a the expense of computation time). See more details on how to fine tune these parameters on the Matlab website