function xnew=gradient_ex(x0) % %%%%% Using user-supplied gradient % options1 = optimset('MaxIter',2,'Disp','off','GradObj','on'); % % x1 = -2:0.1:6; % y1 = zeros(numel(x1),1); % for i=1:numel(x1) % y1(i)=f(x1(i)); % end % %x0 = 1; % % tol = 1e5; % x = x0; % y = f(x0); % count = 1; % shift = 20; % % while (tol > 1e-10 && count < 100 ) % [xnew,cost]=fminsearch(@f,x(count),options1); % 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 % %%%% Not explicitly using the user-supplied gradient options2 = optimset('MaxIter',2,'Disp','off'); x1 = -2:0.1:6; y1 = zeros(numel(x1),1); for i=1:numel(x1) y1(i)=f1(x1(i)); end tol = 1e5; x = x0; y = f1(x0); count = 1; shift = 0.5; while (tol > 1e-10 && count < 100 ) [xnew,cost]=fminsearch(@f1,x(count),options2); x = [x xnew]; ynew = f1(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 %%%%% plotting results always keep this uncommented! :) figure(1); plot(x,y,'--.',x1,y1) text(x(1),y(1)+shift,'x0','FontSize',14) text(x(end),y(end)+shift,'x*','FontSize',14) xlabel('x') ylabel('y') function [out1,grad] = f(x) out1 = 10*x^3-50*x^2+2*x+1; grad = 30*x^2 - 100*x; function out2 = f1(x) out2 = 10*x^3 - 50*x^2+2*x+1; %out2 = abs(x);