Make a custom MATLAB function that can detect all the roots please! Write a MATL
ID: 3108492 • Letter: M
Question
Make a custom MATLAB function that can detect all the roots please!
Write a MATLAB function (IncNR) combining the capabilities of both the Incremental Search Method and the Newton-Raphson Method to find all the roots in a given function [xR, err, n] = IncNR(AF, xb, ed) Inputs: AF = anonymous function xb = initial guess x bracket = [xL xU], where xL = lower x and xU = upper x ed = desired error Outputs: xR = vector of roots err = vector of errors corresponding to the roots n = vector of the number of iterations Suggested Steps: Use the Incremental Search Method to identify the number of roots and the brackets Use the Newton-Raphson Method in each of the brackets starting at either the lower domain or the upper domainExplanation / Answer
Here's the code for the function IncNR with as much documentation as possible.
function [xR,err,n] = IncNR(AF,xb,ed)
%INCNR is a two pronged numerical root finder
% First we sue incremental search on an initial bracket to
% identify several sub-intervals where the roots may reside.
% And then apply Newton-Raphson Method to calculate the root in each of the
% subintervals.
% This we will do by making subroutines Inc and NR which individually do
% the parts mentioned above.
% AF = {f,f'} a cell array of function handles containing f and its
% derivative f', which is needed for Newton-Raphson method
f = AF{1};
df = AF{2};
x0 = Inc(f,xb);
k = size(x0);
xR = zeros(size(x0));
n = zeros(size(x0));
err = zeros(size(x0));
for i=1:k(1)
[xR(i),err(i),n(i)] = NR(f,df,x0(i),ed);
end
end
function [x0] = Inc(F,xb)
% Inc is an incremental search algorithm for finding root.
% Given a function f and initial bracket we will divide the the interval
% into sub intervals by stepping up by 10^-4 and identifying the sign
% change of the function.
x = xb(1):10^-4:xb(2); %creating subintervals
x0 = x(F(x(1:end-1)).*F(x(2:end))<0)'; %Determining subintervals with roots
end
function [xR,err,n] = NR(AF,dAF,x0,ed)
%NR is the Newton-Raphson method to numerically find the root given an
%initial guess of x0 and a desired error to terminate the iterations.
x = x0;
xR = x + AF(x)./dAF(x); %dAF is the derivative of AF
n=1;
while(abs(xR-x)>=ed)
x = xR;
xR = x - AF(x)/dAF(x);
n=n+1;
end
err = abs(xR-x);
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.