MATLAB does not have derivatives built in so let\'s build our own numerical firs
ID: 3688929 • Letter: M
Question
MATLAB does not have derivatives built in so let's build our own numerical first and second lerivative functions. Write a MATLAB function called LastNamemyderivs that takes as input parameters (/, n,xo,c), where n = 1 or n = 2, and returns the 0(h'x) approximation for with (accuracy. Similar to problems 5 & 6 on Homework #4, your program should start with h = 0.5 in the 0(h^4) finite difference formulas, and successively halve h until two successive iterates are within (of one another; it would then return the later iterate as the approximation to message if n is neither 1 nor 2. Write a MATLAB function, railed LastNamenewtonf. that implements Newton's method. Your should take as parameters (f, f) where:rn is the initial eu ess. Your Newton iterationExplanation / Answer
ANSWER b
syms x y; % Make x,y symbolic
f1 = x^2 + y^3 - 1; % Make your two equations (from your example)
f2 = x^4 - y^4 + x*y;
f = [f1; f2]; % f(x) vector
% Jacobian matrix
J = [diff(f1, 'x') diff(f1, 'y'); diff(f2, 'x') diff(f2, 'y')];
% Initial vector
x0 = [1; 1];
% Tolerance:
tol = 1e-10;
Now, make your script into a function:
% To run in MATLAB, do:
% [n, xout, tol] = LastNamenewtonf(f, J, x0, tol);
% disp('n = '); disp(n); disp('x = '); disp(xout); disp('tol = '); disp(tol);
function [n, xout, tol] = LastNamenewtonf(f, J, x0, tol)
% Just to be sure...
syms x, y;
% Initialize error
ep = 1; % Note: eps is a reserved keyword in MATLAB
% Initialize counter
n = 0;
% For the beginning of the loop
% Must transpose into a row vector as this is required by subs
xout = x0';
% Computation loop
while ep > tol && n < 100
g = subs(f, {x,y}, xout); %g(x)
ep = abs(g(1)) + abs(g(2)); %error
Jg = subs(J, {x,y}, xout); %LastNamenewtonf
yout = xout - Jgg; %iterate
xout = yout; %update x
n = n + 1; %counter+1
end
% Transpose and convert back to number representation
xout = double(xout');
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.