Question: MATLAB CODE: Write a function m-file that implements the secant method. Your function should accept the following inputs (in order): A function defining the roots
MATLAB CODE:
Write a function m-file that implements the secant method. Your function should accept the following inputs (in order):
- A function defining the roots problem
- A vector of two initial guesses (first element is the first guess, second element is second guess)
- A stopping criterion ( es ) for the numerical solution with a default value of 1e-5
- A maximum iteration count for the numerical solution with a default value of 30
- An arbitrary number of parameter values associated with the roots problem
Your function should output the following four scalar outputs (in order):
- The root estimate
- The residual in the numerical solution
- The approximate relative error in the numerical solution
- The number of iterations required for convergence
Code:
function [xroot,residual,ea,iter_count] = student_solution(fun,xi,es,max_it,varargin)
if nargin < 2, error('Two few inputs, read help comments'), end
if nargin<3||isempty(es), es=1e-5;end
if nargin<4||isempty(max_it), max_it=30;end
xr_loop = zeros(max_it,1);
xr_loop(1) = xi(1);
xr_loop(2) = xi(2);
counter = 0;
for iter = 3:max_it
xr_loop(iter) = xr_loop(iter-1) - (fun(xr_loop(iter-1),varargin{:})*(xr_loop(iter-2) - xr_loop(iter-1)))/(fun(xr_loop(iter-2),varargin{:}) - fun(xr_loop(iter),varargin{:}));
counter = counter + 1;
if xr_loop(iter) ~= 0
ea = (xr_loop(iter)-xr_loop(iter-1))/xr_loop(iter);
end
if abs(ea) <= es
break
end
end
iter_count = counter
xroot = xr_loop(iter)
residual = roots(fun)- xroot
display(ea)
end
*PLEASE EDIT CURRENT CODE NOT SOMETHING NEW AND PLEASE DON'T ANSWER WITH AN ANSWER THAT IS ALREADY ON CHEGG
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
