% This is a sample script file showing you how to plot the contours % in homework problem 2. It uses the implot.m file on our class % website (also available on Matlab's website). %% Problem: Plot several contours of the function z=sin^2(x)+(1/4)*y^2 %Window size: [xmin, xmax, ymin, ymax] winsize=[-2 2 -2 2]; %Define the function (only the zero level curve is plotted) % This is the level curve at z=0.1 f=inline('sin(x).^2+0.25*y.^2-0.1','x','y'); implot(f,winsize) hold on %Allows you to draw over the previous plot % This is the level curve at z=0.5 f=inline('sin(x).^2+0.25*y.^2-0.5','x','y'); implot(f,winsize) % This is the level curve at z=0.75 f=inline('sin(x).^2+0.25*y.^2-0.75','x','y'); implot(f,winsize) % This is the level curve at z=1.0 f=inline('sin(x).^2+0.25*y.^2-1.0','x','y'); implot(f,winsize) %% Now we'll compute some points on the trajectory of the gradient descent f=inline('sin(x).^2+0.25*y.^2','x','y'); df=inline('[ 2*sin(x), 0.5*y]','x','y'); x=[1.3,1.1]; alpha=0.7; for j=1:20 x=x-alpha*df(x(1),x(2)); X(j,:)=x; end %And plot them plot(X(1,:),X(2,:),'k-*') hold off %We could also plot them by iteration: figure(2) plot(X)