In MATLAB language please Write a function function [xroot, f root] = secant roo
ID: 3792348 • Letter: I
Question
In MATLAB language please Write a function function [xroot, f root] = secant root (func, xl, xu) that takes a function func and returns the approximate root xroot as well as the function value froot at the approximate root; x1 and xu are the lower and upper bound of the secant interval, respectively. Secant root formula: x_root x_u - f(x_u) middot (x_1 - x_u)/f(x_1) - f(x_u), f_root = f(x_root) Test your function with the following input (define w(t), y(x) as anonymous functions in the workspace): y(x) = x^3, x_1 = -5, x_u = 5 w(t) = sin (t), t_1 = 2, t_u = 5 w(t) = sin (t), t_1 = 3, t_u = 4Explanation / Answer
Main Function tto call the sacant function for all three problems:
%% MATLAB Code for sacant method
clc;
close all;
clear all;
disp('Solution for a :')
y=@(x) x^3;
[xroot, froot]= secantroot(y,-5,5)
disp('Solution for b :')
w=@(t) sin(t);
[xroot, froot]= secantroot(w,2,5)
disp('Solution for c :')
w=@(t) sin(t);
[xroot, froot]= secantroot(w,3,4)
%% Code of the function. Both main and function should be stored in same directory.
%% program strats here
function [xroot, froot]=secantroot(func,xl,xu)
xroot=xu-(func(xu)*(xl-xu)/(func(xl)-func(xu)));
froot=func(xroot);
maxerr=10^-4; flag = 1; maxiter = 100;
c = xroot;
while abs(froot) > maxerr
if func(xu)*func(c)<=0
xl = c;
elseif func(xl)*func(c)<=0
xu=c;
end
c= xu-(func(xu)*(xl-xu)/(func(xl)-func(xu)));
flag = flag + 1;
if(flag == maxiter)
break;
end
end
xroot = c;
froot=func(c);
Output :
Solution for a :
xroot =
0
froot =
0
Solution for b :
xroot =
3.1416
froot =
1.2246e-16
Solution for c :
xroot =
3.1416
froot =
1.2246e-16
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.