contour and steepest function
Show older comments
I tried it but I couldn't do it, please help. thanks.
In this problem, you will do some further experiments with contour. Recall the steepest descent algorithm you programmed in Assignment 3. There, we had used the steepest descent algorithm to solve the following optimization problem (iteratively): min x∈R2 f(x) = 1 2 xTAx−xTb (1) Now we want to plot the path taken by the iterates of the algorithm over the contour plot of f(x). The function showPath.m which you can download from course webpage does this; this function has the following header: showPath(A,b,XVals) Here A and b characterize (1), and the matrix XVals contains the iterates of the steepest descent algorithm as its rows; that is XVals looks like the following XVals = -3.0000 -2.0000 -1.3589 -0.1245 -0.3634 -0.9956 0.0414 -0.5329 0.2870 -0.7478 . . . First, you need to revise your steepest descent routine so that the iterates of the algorithm are stored as rows of the matrix XVals. Then, revise the function header to have XVals as another output: function [x F it XVals] = steep(x0, A, b, itmax) Then, you can use showPath to plot the path taken by the iterates. Run your tests on the following problem. A =2 0 0 6, b = 1 −4, x0 =−3 −2. Your result at this point should like Figure 1. Once you have everything working, revise showPath by having more contour lines and having the contour lines labeled (using clabel). Submit the revised steep and showPath functions and your final plot.
steepest code
function [x F iter ]=steep (x0,A,b,itmax)
x = x0;
iter = 0;
tol=10^-6;
while norm (Df(x,A,b)) > tol && ( iter <=itmax)
iter= iter +1;
p= b-A*x;
a= dot(p,p)/dot(A*p,p);
x= A\b;
F= 1/2*x'*A*x-x'*b;
end
function y = Df(x,A,b)
y =b-A*x;
function showPath(A, b, XVals)
close all;
f = @(x, y)( 0.5*(x.^2*A(1,1) + x.*y*A(2,1) + x.*y*A(1,2) ...
+ y.^2*A(2,2)) - x*b(1) - y*b(2));
h = .1;
% contour plot
x = [-4 : h : 5];
y = [-4 : h : 3];
[X Y] = meshgrid(x,y);
Z = f(X,Y);
contour(X,Y,Z);
grid on;
hold on;
% Plot the trajectory
plot(XVals(:,1),XVals(:,2), '-r*', 'linewidth', 2, 'markersize',2);
hold off
Answers (0)
Categories
Find more on Contour Plots in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!