In: Computer Science
For a function, only the numerical values are available as shown in the table bellow, Write a MATLAB script file to calculate the derivative of y, use a ‘for loop’ to apply the centered method to the middle 8 points. Hint: Define x and y as arrays, so you can easily call them in formula and the for loop
xi = 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0
yi = 1.815 2.16 2.535 2.94 3.375 3.84 4.335 4.86 5.415 6
Answer:----
Given,
xi = 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0
yi = 1.815 2.16 2.535 2.94 3.375 3.84 4.335 4.86 5.415 6
MATLAB script file to calculate the derivative of y, use a ‘for loop’ to apply the centered method to the middle 8 points
Here the code is
%Define function
function ff= forward(yi,xi,p)
%Find value
ff= (yi(p + 1) - yi(p)) / (xi(p + 1) - xi(p));
%End
end
%Define function
function bb= backward(yi,xi,p)
%Find value
bb = (yi(p) - yi(p - 1)) / (xi(p) - xi(p - 1));
%End
end
%Define function
function cc= central(yi, xi, p)
%Find value
cc = (yi(p + 1) - yi(p - 1)) / (xi(p + 1) - xi(p - 1));
%End
end
%Define xi
xi=[1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0];
%Define yi
yi=[1.815 2.16 2.535 2.94 3.375 3.84 4.335 4.86 5.415 6];
%Define value
size =10;
%Define value
di=zeros(size,1);
%Call Function
di(1) = forward(yi, xi, 1);
%Loop
for n = 2:size-1
%Call Function
di(n) = central(yi, xi, n);
end
%Call Function
di(size) = backward(yi, xi, size);
%Display message
fprintf('\n %s %s %s','xi', 'yi', 'Derivative');
%For loop
for n=1:10
%Display message
fprintf('\n %.2f %.3f %.3f',xi(n), yi(n), di(n));
%End
end
The sample output :---