Write a MATLAB function (IncNR) combining the capabilities of both the Increment
ID: 3805318 • Letter: W
Question
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) 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
Ans: The matlab code for the question is :
function [xR,err,n,xRV,errV,AFD1,AFD2] = NewtonRaphsonNM(AF,xi,ed)
% AF = anonymous function equation:
% ed = desired approximate relative error = |(current - previous)/current|: ed = 0.01;
% xR = x root
% xRV = x root vector
% errV = approximate relative error vector
% AFD1 = anonymous function 1st derivative
% AFD2 = anonymous function 2nd derivative
%% Computations
% Derivatives
AFSYM = sym(AF); % symbolic math function
AFD1SYM = diff(AFSYM); % symbolic math function 1st derivative
AFD2SYM = diff(AFD1SYM); % symbolic math function 2nd derivative
AFD1 = matlabFunction(AFD1SYM); % anonymous function 1st derivative
AFD2 = matlabFunction(AFD2SYM); % anonymous function 2nd derivative
% Newton-Raphson Method
err = 1; % initial approximate relative error = 100%
k = 1; % initial counter
while ed < err % compares desired versus calculated error
xR = xi-(AF(xi)/AFD1(xi)); % x root using Newton-Raphson method
xRV(k+1) = xR; % stores the x root per iteration in a vector
err = abs((xRV(k+1) - xRV(k))/xRV(k+1)); % approximate relative error
errV(k+1) = err; % stores the error into a vector
xi = xR; % new guess x = xR, where xR = x root
k = k+1; % increase counter
end
n = k - 1; % number of iterations
xRV = xRV(2:end); % readjust x root vector
errV = errV(2:end); % readjust approximate relative error vector
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.