%This demonstrates the steepest descent algorithm, using it to find the minimum of
%f(x)=cos(3x)-sin(x)+2 in the interval -2<x<2, using 2 different initializations.
%15 iterations with step size a=0.0.5. One initialization converges to local minimum.
clear;t=linspace(-2,2,1000);f=cos(3*t)-sin(t)+2;
figure,plot(t,f),grid on,hold on
%Initialize using -0.2:
uinit=-0.2;u=uinit;a=0.05;for n=1:15;fu=cos(3*u)-sin(u)+2;   
plot(u,fu,'g+'),hold on,u=u-a*(-cos(u)-3*sin(3*u));end
%Initialize using 0.1:
vinit=0.1;v=vinit;a=0.05;for n=1:15;fv=cos(3*v)-sin(v)+2;   
plot(v,fv,'r+'),hold on,v=v-a*(-cos(v)-3*sin(3*v));end
