MATLAB Examples

# Global Minimization of 1D Equation

Customer provided this example where he was puzzled why fmincon had a hard time finding the mimimum value.

```Copyright (c) 2010, The MathWorks, Inc.

## Equation to minimize

```f = @(x) x.*sin(x) + x.*cos(2.*x); ```

## Bounds

```lb = 0; ub = 10; ```

## Find Minimum and Plot

```x0 = [0 1 3 6 8 10]; hf = figure; for i=1:6 x(i) = fmincon(f,x0(i),[],[],[],[],lb,ub,[],... optimset('Algorithm','SQP','Disp','none')); subplot(2,3,i) ezplot(f,[lb ub]); hold on plot(x0(i),f(x0(i)),'k+') plot(x(i),f(x(i)),'ro') hold off title(['Starting at ',num2str(x0(i))]) if i == 1 || i == 4 ylabel('x sin(x) + x cos(2 x)') end end ```

## A common GOTCHA!

This problem is a 1D bounded minimization problem. There is a specialized solver for this type of problem: fminbnd.

```x2 = fminbnd(f,lb,ub) figure ezplot(f,[lb ub]); hold on plot(x2,f(x2),'ro') hold off ylabel('x sin(x) + x cos(2 x)') title({'Solution using fminbnd.','Required no starting point!'}) ```
```x2 = 4.7954 ```

Leason Learned: Use the appropriate solver for your problem type!

## But what if fmincon was the only choice?

Use globalSearch or MultiStart

```problem = createOptimProblem('fmincon','objective',f,'x0',x0(1),'lb',lb,... 'ub',ub,'options',optimset('Algorithm','SQP','Disp','none')); gs = GlobalSearch; xgs = run(gs,problem); figure ezplot(f,[lb ub]); hold on plot(xgs,f(xgs),'ro') hold off ylabel('x sin(x) + x cos(2 x)') title('Solution using globalSearch.') ```
```GlobalSearch stopped because it analyzed all the trial points. All 23 local solver runs converged with a positive local solver exit flag. ```