Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The Secant Method in Matlab Write a Matlab function to locate a root by the seca

ID: 3849769 • Letter: T

Question

The Secant Method in Matlab Write a Matlab function to locate a root by the secant method. Your function should be put in the file mysecant.m, and should be called as x=mysecant(f, x0, x1, tol, nmax) Here f is the function f, x0, x1 are the initial guesses, tol is the error tolerance, nmax is the maximum number of iterations, and x is the output of your function. Test your function to find the value Squareroot 2, as the root for f(x) = x^2 - 2, to see if it works. Use sprintf and "disp" to display your result in each iteration, so you can check the convergence. Then, use it to find a root for the function f(x) = e^-x - cos(x) in the interval [1.1, 1.6]. Use tol = 1e-12 and nmax=10. Your two initial guesses should be on the interval [1.1, 1.6]. How does the result compare to those with Newton's method? Comment in detail. What to hand in: Your file mysecant.m, test result for f(x) = x^2 - 2, and the result for f(x) = e^-x - cos(x).

Explanation / Answer

Answer for the Given Question:

As per the given conditions in the problem based on that written the below mthod with comments and function defintaion.

function [x,error] = mysecant(f,x0,x1,tol,nmax)
% Input Arguments:
% f is the function
% x0 and x1 are the two initial guesses
% - tol is the error tolerance
% - nmax is the maximum number of iterations reached in case of NOT convergence

% Output Arguments:
% - x is the vector of iterates

% put the first two initial guesses given inside of the vector x of
% iterates
x(1)=x0;
x(2)=x1;
for i=3:nmax % why do we start this loop at 3? because the first two entries
% of the vector of iterates x have already been assigned
if (f(x(i-1))-f(x(i-2)))==0
disp('Error: we are dividing by zero!');
break;
end
x(i)=x(i-1) - f(x(i-1))*(x(i-1)-x(i-2))/(f(x(i-1))-f(x(i-2)));
error(i-2)=abs(x(i-1)-x(i-2)); % assign the error as the difference of the
% two last iterates found
if (error(i-2)<=tol) % the error assignment is shifted by 2 because the for loop
% started from i=3
return;
end
end

end

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote