Use MATLAB to approximate f=0 using the secant method; fill in the code as indic
ID: 671149 • Letter: U
Question
Use MATLAB to approximate f=0 using the secant method; fill in the code as indicated by the comments.
function [xi,fi,n] = secant(f,xo,x1,tolr)
% Initialize
nmax = 100; % maximum number of iterations
% Vector of x iterates
xi = zeros(nmax+1,1);
xi(1) = xo;
xi(2) = x1;
% Vector of function values
fi = zeros(nmax+1,1);
fi(1) = f(xo);
fi(2) = f(x1);
error = tolr + 1; % error
count = 1; % iteration count
while error > tolr && count < nmax
count = count + 1;
% Find the avg slope, using xo and x1
mave = % !! FILL IN CODE HERE!!
% Check for zero average slope: if average slope = 0, make xi, fi, and n equal to nan, and print out a warning, and return
% !!! FILL IN CODE HERE!!!
% Update xo and x1 iteraterations
xo = % !! FILL IN CODE HERE!!
x1 = % !! FILL IN CODE HERE!!
% Store results in vectors
xi(count+1) = % !! FILL IN CODE HERE!!
fi(count+1) = % !! FILL IN CODE HERE!!
% Compute the error (using the last two iterates of x)
error = % !! FILL IN CODE HERE !!
end
% Discard the variables you don’t need
n = count;
xi = xi(1:n+1);
fi = fi(1:n+1);
Explanation / Answer
function [xi,fi,n] = secant(f,x0,x1,tolr)
% Initialize
nmax = 100; % maximum number of iterations
% Vector of x iterates
xi = zeros(nmax+1,1);
xi(1) = x0;
xi(2) = x1;
% Vector of function values
fi = zeros(nmax+1,1);
fi(1) = f(x0);
fi(2) = f(x1);
error = tolr + 1; % error
count = 1; % iteration count
while error > tolr && count < nmax
count = count + 1;
% Find the avg slope, using xo and x1
% !! FILL IN CODE HERE!!
mave = (x0*f(x1)-x1*f(x0))/(f(x1)-f(x0));
% Check for zero average slope: if average slope = 0, make xi, fi,
% and n equal to nan, and print out a warning, and return
% !!! FILL IN CODE HERE!!!
if(mave==0)
x0=NAN;
f(x0)=NAN;
count=NAN;
disp('error');
exit;
end
% Update xo and x1 iteraterations
x0 = x1;% !! FILL IN CODE HERE!!
x1 = mave;% !! FILL IN CODE HERE!!
% Store results in vectors
xi(count+1) = x0;% !! FILL IN CODE HERE!!
fi(count+1) =x1; % !! FILL IN CODE HERE!!
% Compute the error (using the last two iterates of x)
error = x(count+1)-x(count);% !! FILL IN CODE HERE !!
end
% Discard the variables you don’t need
n = count;
xi = xi(1:n+1);
fi = fi(1:n+1);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.