% Script 3 for Week 2 % Example of incremental search in action. f2=@(x) exp(x)-tan(x); f1=@(x) x.^2-8; incsearch(f1,-3,3) incsearch(f1,ans(1,1),ans(1,2)) % Below are the contents of the varlist.m and testvarargin.m function files, used it to test our understanding of the varargin cell array. %******************************* function varlist(varargin) fprintf('\n Number of arguments: %9d \n',nargin) celldisp(varargin) %****************************** varlist(ones(3),'some text',pi) %****************************** function [x a b c]=testvarargin(x, varargin) a=varargin{1}; b=varargin{2}; c=varargin{3}; fplot(@(t)a*sin(b*t+c),[-pi,pi]) end %****************************** testvarargin(3, 4, 5, 6) [x a b c]=testvarargin(3, 4, 5, 6) % More on fixed-point iteration. % This is a solution method producing a sequence of approximate solutions that MIGHT converge to a real solution. % Suppose want to find x where exp(-x)-x = 0. % So x=exp(-x) % Let's try a quick plot so we can estimate the solution from that. t=-1:.1:2; plot(t,exp(-t),t,t) % Now define a function whose fixed point is our desired solution. g=@(x) exp(-x); x=5 x=g(x) % We want to know where g(x)=x. % Form a sequence starting with some seed value: x_0=seed value. % Iterate x=g(x) by hitting the up-arrow and return repeatedly. % x_1=g(x_0) % x_2=g(x_1) % . % . % . % x_{n+1}=g(x_n). % Stop this procedure when ea=abs( (x(i+1)-x(i))/x(i+1) ) % is less than a designated target value (if it ever is less.) % Often the sequence converges and when it does it converges to the x value with x=g(x). % If it doesn't YOU CAN OFTEN REFORMULATE THE ORIGINAL EXPRESSION and create an equivalent NEW g that does work. You will prefer a g with a smaller derivative (less than magnitude 1) near the fixed point. % Now on to some 3-d graphing. % meshgrid lets you avoid writing a little % loop to calculate z values in a surface plot. % For a square domain you can use [x,y] = meshgrid([-2:.2:2]); Z = x.*exp(-x.^2-y.^2); surf(x,y,Z) colorbar % For a more general rectangular domain you use [x,y] = meshgrid([-2:.2:2],[-1:0.2:1]); Z = x.*exp(-x.^2-y.^2); surf(x,y,Z) colorbar X2=[-2:.2:2]; Y2=[-2:.2:2]; for i=1:length(X2) for j=1:length(Y2) Z2(i,j)=X2(i)*exp(-X2(i)^2-Y2(j)^2); end end figure(7) surf(X2,Y2,Z2) colorbar % Testing the Newton-Raphson script: y = @(m) sqrt(9.81*m/0.25)*tanh(sqrt(9.81*0.25/m)*4)-36; dy = @(m) 1/2*sqrt(9.81/(m*0.25))*tanh((9.81*0.25/m) ... ^(1/2)*4)-9.81/(2*m)*sech(sqrt(9.81*0.25/m)*4)^2; newtraph(y,dy,140,0.00001)