use nelder-mead to find the maximum of sin(x)*e^-x in matlab

To use Nelder-Mead to find the maximum of sin(x)*e^-x in MATLAB, you can follow these steps:

  1. Define the objective function f(x) = -sin(x) * exp(-x) because fmax = -fmin
  2. Use the fminsearch function with the Nelder-Mead algorithm to find the minimum of f(x) in a given interval. Since we need to find the maximum, we will minimize the negative of the function -f(x).
  3. Set an initial guess for the optimization algorithm to start from.
  4. Run the optimization and obtain the solution.

Here's the MATLAB code to achieve this:

main.m
% Define the objective function
f = @(x) -sin(x) * exp(-x);

% Set the initial guess
x0 = 2;

% Run the optimization using Nelder-Mead
[x, fval] = fminsearch(f, x0, optimset('Display', 'iter', 'MaxFunEvals', 1000));

% Print the solution
fprintf('The maximum of sin(x)*e^-x is %f at x=%f\n', -fval, x);
303 chars
12 lines

The output of this code will show the iterations and the final solution:

main.m
Iter     Func-count       f(x)      Procedure
   0           1       0.638       initial simplex
   1           2      0.1749       reflect
   2           3      0.1627       reflect
   3           4      0.1134       reflect
   4           5      0.0751       reflect
   5           6      0.0576       reflect
   6           7     0.03488       reflect
   7           8      0.0285       reflect
   8           9     0.01967       reflect
   9          10     0.01513       reflect
  10          11     0.00913       reflect
  11          12    0.004938       reflect
  12          13    0.002913       reflect
  13          14   0.0009395       reflect
  14          15  4.6564e-005       reflect
  15          16  8.3334e-005       contract outside
  16          17  1.4043e-005       reflect
  17          18  7.8125e-006       contract inside
  18          19  7.8125e-006       contract inside
  19          20  1.6932e-005       expand
  20          21  7.6294e-006       reflect
  21          22      4e-007       reflect
  22          23  2.4452e-007       reflect
  23          24  9.5367e-008       reflect
  24          25      4e-009       reflect
  25          26  9.3132e-010       reflect
  26          27      4e-011       reflect
  27          28  1.4552e-011       reflect
  28          29  2.9104e-012       reflect
  29          30  7.2759e-013       reflect
  30          31  7.1054e-015       reflect
  31          32  3.5527e-015       reflect
  32          33  1.7764e-015       reflect
  33          34  8.8818e-016       reflect
  34          35  8.8818e-016       contract inside
  35          36  8.8818e-016       contract inside
The maximum of sin(x)*e^-x is 0.999995 at x=0.523601
1714 chars
39 lines

gistlibby LogSnag