Task 5: A backward difference for Numeric differentiation Routine (8 pts) Use MA
ID: 3184051 • Letter: T
Question
Task 5: A backward difference for Numeric differentiation Routine (8 pts) Use MATLAB to write a function called backwarddiff.m that takes data sample locations and function samplings at those locations as inputs and returns an approximation of the derivative at the sample points based on backward finite difference method with order of accuracy O (h'). The function should display nothing to the screen unless an error or warning occurs. The detailed specification is as follows: The approximation of derivative by backward difference method (for O (h)) is given as 3f (x)-4 f (x,-)+ f(x-) f "(x)= 2 h backwarddiff(x, fx) x : (N-element vector) numerical data for sample locations. fx: (N-element vector) function data taken at locations defined in input x. IApproximation for the first derivative of fx at data point. Valid call: Inputs: Output: Assumptions: The ith element of x corresponds to the ith element of fx. Validation: Your code should throw an error if any of the following are true x and fix are not the same length either of the inputs are not vectors (e.g., a matrix) either of the inputs contains something other than numerical data · Hint: functions like isvector and isnumeric() may come in handy during input validation. Do not call any specialized MATLAB functions that perform differentiation. Write it from scratch.Explanation / Answer
function backwarddiff(x,fx )
% derivative f'(x)=(3f(x)-4f(x-h)+f(x-2h))/2h : three point rule
N=length(x);
M=length(fx);
if(N~=M)
disp('lenght of x and fx are different')
end
a=isvector(x)
b=isvector(fx)
if(( a~= 1))
disp('input x are not vectors')
end
if(( b~=1))
disp('input fx are not vectors')
end
c=isnumeric(x);
d=isnumeric(fx);
if((c~=1))
disp('not entered numerical data x')
end
if((d~=1))
disp('not entered numerical data fx')
end
delx=(x(end)-x(1))/(length(x)-1);
df3x=zeros(length(x)-2);
df3x=(3*fx(1:end-2)-4*fx(2:end-1)+fx(3:end))/(delx);
end
%---------------------------Testing------------------
input: >>x=[1 1 1];y=[2 2];backwarddiff(x,y)
output: >> lenght of x and fx are different
input: >> x='#'; y=[3 2 2]; backwarddiff(x,y)
output: >> not entered numerical data x
input:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.