Solutions to Prelim 2 Review Questions -------------------------------------- %------------------------------------- % Insight Ch4 Sec1 #5 % Solicits input for values a, b,c and prints the length of a:c:b and the % distance from the last vector component to b. a = input('a = '); b = input('b = '); c = input('c = '); v = a:c:b; fprintf('The length of a:c:b is %d.\n', length(v)) fprintf('The distance from v(end) to b is %f.\n', v(end)-b) % Note: When used as an index, the keyword end is the same as the % length of the vector. So the distance from the last vector component to % b can be written as v(length(v)) - b %------------------------------------- % Insight Ch4 Sec1 #6 x = 1:10:100; while length(x) < 1000 x = [x x(1) x]; end fprintf('length(x) = %d.\n',length(x)); % Note: If the length of x in iteration k is N, then after iteration k+1 % the length of x is 2*N + 1. At the start length(x) = 10 so as the loop % progresses the length of x is % 10, 21, 43, 87, 175, 351, 703, 1407. %------------------------------------- % Insight Ch4 Sec1 #11 % Generate a length-10 vector according to a recursion formula. n = input('n = '); f = zeros(1,10); for k=1:10 if k==1 % Starting value f(k) = n; elseif rem(f(k-1),2)==1 % f(k-1) is odd f(k) = 3*f(k-1) + 1; else % f(k-1) is even f(k) = f(k-1)/2; end end plot(1:10,f,'*') % Plot the result using the star-marker %------------------------------------- % Insight Ch4 Sec3 #3 % Evaluate error % e_h(x) = abs( (sin(x+h)-sin(x))/h - cos(x) ) = big_O(h) clc x = input('Enter a real number in [0,2pi]: '); n= 16; h= 1./logspace(1,n,n); e_h= zeros(1,n); e_best= Inf; disp(' h error ') for k= 1:n e_h(k)= abs( (sin(x+h(k))-sin(x))/h(k) - cos(x) ); fprintf('%.0e %.4e \n', h(k), e_h(k)) if e_h(k) 1 num = num + 1; end end fprintf('Probability that connecting chord is longer than 1 is %f\n', num/N) %------------------------------------- % Insight Ch6 Sec1 #19a function p = ProbG(L,R) % p is the area under the Gaussian function (bell curve) between L and R % initialize... N= 10000; % Number of trials count = 0; % Number of points under the curve % count the number of random points that lie beneath the curve for i = 1:N % Random point in the rectangle bounded by x=L, x=R, y=0, and y=1 x= rand(1)*(R-L)+L; y= rand(1); % If the point is under the curve, i.e. f(x), then count as a "hit." if y <= (2*pi)^(-1/2) * exp(-x^2/2) count=count+1; end end % Monte Carlo estimate of area under the curve p= (count/N)*(R-L); %------------------------------------- % Insight Ch6 Sec2 #8 function [x, y, z] = RandomWalk3D(n) % Random walk in 3D. x,y,z are vectors representing the path. % The kth step has the coordinates (x(k),y(k),z(k)). %initialize coordinates and counter xc=0; yc=0; zc=0; k=0; %while not on the boundary, take a random step while abs(xc)