write a functioni = csimpson(f,h) that takes as inputs f an array of function values and h the distance between grid values and computes i the composite simpson’s approximation of the integral in matlab
main.m
functioni = csimpson(f,h)% csimpson calculates the composite simpson's approximation of the integral.%% Syntax: i = csimpson(f,h)%% Inputs: % f - an array of function values% h - the distance between grid values%% Outputs:% i - the composite Simpson's approximation of the integral.%% Example:% f = [1 2 3 4 5 6 7 8];% h = 1;% i = csimpson(f,h); % i = 15%% Author: Divyaprakash Mummidi% Date: 1st September 2021 n = length(f)-1;
i = 0;
% If the number of segments is not even% then we use the trapezoidal rule for the last segmentif(mod(n,2) ~= 0)
i = i + trapezoidal(f(n:n+1), h);
n = n-1;
end% Simpson's rule for the rest of the segmentsforj=1:2:n
i = i + simpson(f(j:j+2), h);
endendfunctions = simpson(f,h)% simpson calculates the simpson's approximation of the integral.% Simpson's rule is used for every segment except the last one.%% Syntax: s = simpson(f,h)%% Inputs: % f - an array of function values% h - the distance between grid values%% Outputs:% s - the Simpson's approximation of the integral.%% Author: Divyaprakash Mummidi% Date: 1st September 2021 s = (h/3) * (f(1) + 4*f(2) + f(3));
endfunctiont = trapezoidal(f,h)% trapezoidal calculates the trapezoidal approximation of the integral.% Trapezoidal rule is used for the last segment.%% Syntax: t = trapezoidal(f,h)%% Inputs: % f - an array of function values% h - the distance between grid values%% Outputs:% t - the trapezoidal approximation of the integral.%% Author: Divyaprakash Mummidi% Date: 1st September 2021 t = (h/2) * (f(1) + f(2));
end