# How to find extrema using Matlab symbolic operations

You need to download the file `ezcontourc.m`.

Example: Find all relative maxima and minima of f(x,y) = x3 - 3x + 3xy2

Define the symbolic variables and `f`

```syms x y
f = x^3 - 3*x + 3*x*y^2
```

Find the partial derivatives

```fx = diff(f,x)
fy = diff(f,y)```

Find critical points (`xc,yc)` by solving `fx`=0 and `fy`=0 for `x` and `y`

`[xc,yc] = solve(fx,fy,x,y); [xc,yc]`

Matlab finds 4 solutions. The first solution is `xc(1),yc(1)`,..., the 4th solution is `xc(4),yc(4)`.

Find the second partials and the discriminant `D`

```fxx = diff(fx,x); fxy = diff(fx,y); fyy = diff(fy,y)
D = fxx*fyy - fxy^2```

Evaluate `D` at the first critical point by substituting for `x` and `y` the values `xc(1)` and `yc(1)`

```subs(D,{x,y},{xc(1),yc(1)})
subs(fxx,{x,y},{xc(1),yc(1)})```

Note that we have `D` > 0 and `fxx` > 0, hence this is a relative minimum.

We can similarly check the other three critical points and find that two of them are saddle points and one is relative maximum.

Plot the function as a surface and as contours (with 51 contours)

```figure(1); ezsurf(f,[-1.5,1.5,-1.5,1.5]);
figure(2); ezcontourc(f,[-1.5,1.5,-1.5,1.5],51); axis equal; axis tight```
Can you see the relative maximum, relative minimum and the two saddle points in the contour plot?