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

Code in MATLAB a function which the Test Cases below are to verify correct code.

ID: 3817702 • Letter: C

Question

Code in MATLAB a function which the Test Cases below are to verify correct code.

Write a function with the header [df] = my Partial Deriv (f, x, ind, eps) which calculates the partial derivative using the central difference method of function f with respect to x (ind). The central difference approximation of a function evaluated at x is: f' = f(x + h) - f(x - h)/2 element and eps is used to permute x (ind) such that when ind = 1: h = [element 0 0], when ind = 2: h = [0 element 0] and when ind = 3: h = [0 0 element] f_1(x, y, z) = 9x^2 + 36y^2 + 4z^2 - 36 f_2(x, y, z) = x^2 + 2y^2 - 20z f_3(x, y, z) = x^2 - y^2 + z^2 >> f1 = @ (x) 98 x(1).^2 + 36* x(2)^2 + 4*x(2)^2 + 48x(3).^2 - 36; >> f2 = @ (x) x(1).^2 - 2*x(2).^2 - 20*x(3); >> f3 = @ (x) x(1).^2 - x(2) - x(2).^2 + x(3).^2; >> x = [-1; 0; -1]; >> s = my Partial Deriv (f1, x, 1, le-7) s = -17.9999999971869 >> s = my Partial Deriv (f2, x, 3, le-7) s = -20.0000000027956 >> s = my Partial Deriv (f3, x, 1, le-7) s = -2.00000000116773 >> s = my Partial Deriv (f3, x, 2, le-7) s = 0 >> my F = @ (x) 4 *sin (x) + exp (x); >> my Partial Deriv (myF, x, 1, le-6) >> my Partial Deriv (myF, pi/17, 1, le-6) ans = 5.1349 You can implement this function with three lines of code. (Or fewer.)

Explanation / Answer

please create file myPartialDeriv.m and paste below code

function s = myPartialDeriv(f,x,ind,eps)
format long;
%choosing h depending on index given
if ind == 1
h = [eps;0;0];
elseif ind == 2
h = [0;eps;0];
else
h = [0;0;eps];
end

%calculating x+h and x-h
x_plus_h = x + h;
x_minus_h = x - h;


f(x_plus_h); %evaluating f @ x+h
f(x_minus_h); %evaluating f @ x-h
%using central difference formula
s = (f(x_plus_h) - f(x_minus_h)) / (2 * eps);

please refer below output

>> f1 = @(x) 9*x(1).^2 + 36*x(2).^2+4*x(3).^2-36;
>> f2 = @(x) x(1).^2 - 2*x(2).^2-20*x(3);
>> f3 = @(x) x(1).^2 - x(2).^2 + x(3).^2;
>> x = [-1;0;1];
>> s = myPartialDeriv(f1,x,1,1e-7)

s =

-17.999999997186933

>> s = myPartialDeriv(f2,x,3,1e-7)

s =

-20.000000002795559

>> s = myPartialDeriv(f3,x,1,1e-7)

s =

-2.000000001167734

>> s = myPartialDeriv(f3,x,2,1e-7)

s =

0

>>
>> myF = @(x) 4*sin(x) + exp(x);
>> s = myPartialDeriv(myF,x,1,1e-7)

s =

2.529088665159662
0
0

>> s = myPartialDeriv(myF,pi/17,1,1e-7)

s =

5.134869699441325
0
0

>>

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