function xnew=direct_ex(x0) options = optimset('MaxIter',2,'Disp','off'); %x0 = 1; tol = 1e5; x = x0; y = f(x0); count = 1; while (tol > 1e-10 && count < 100 ) [xnew,cost]=fminsearch(@f,x(count),options); x = [x xnew]; ynew = f(xnew); y = [y ynew]; disp(['The new point is: ',num2str(xnew)]) disp(['The residual is: ',num2str(cost)]) count = count+1; tol = abs(x(count) - x(count-1)); end x1 = -2:0.1:6; y1 = zeros(numel(x1),1); for i=1:numel(x1) y1(i)=f(x1(i)); end figure(1); plot(x,y,'k--.',x1,y1) text(x(1)+.15,y(1)+5,'x0','FontSize',14) text(x(end)+.15,y(end)+5,'x*','FontSize',14) xlabel('x') ylabel('y') function out1 = f(x) out1 = 10*x^3-50*x^2+2*x+1; %out1 = abs(x);