Can someone please solve the following problem using MATLAB language? Could you
ID: 3348314 • Letter: C
Question
Can someone please solve the following problem using MATLAB language? Could you also please comment your code, that would be very helpful. Here are some hints and tips. Thanks!
Homework Problem 2: Numerical Integration In this problem, you will create a function to compute integrals using the composite Simpson's Rule. For an interval of integration [a,b], Simpson's rule approximates definite integrals as: Divide [a,bl into n equal sub-intervals of length h to obtain the composite Simpson's Rule: where x a jh and h (b-a)/n. Note that n must be even Create a function called Simpson to evaluate the definite integral of a given function fx) on an interval a,b Your function must take in input arguments a) f- a function handle b) a lower limit of integration c) b - upper limit of integration d) tol - tolerance. The output arguments should be I - the value of the integral and h - the sub-interval length. Your function should be written as follows Set 2 and use Equation (4) to compute a first approximation lold Inside a loop, set lold-I. Then, double n and compute I with Equation (5). The stopping criterion should be when I > t simp,h]Simpson ((x) cos (x)0,pi/2,1e-3) t-simp = 1.0000 0.1963 >>tsimp-1 ans- 8.2955e-06 Store the code of this problem in the filename Simpson.m. This file must go into your zipped folder as it will be evaluatedExplanation / Answer
Here is the function Simpson designed as per given instructions. It was designed using MATLAB R2014A. If you have any question or double in the code, please let me know.
Remark : First estimate should be I so that Iold = I works correctly inside the loop. If we set first estimate to Iold then it will give error by saying Undefined function or variable as I will not be present in the memory till that point.
==========================================================
function [I, h] = Simpson(f, a, b, tol)
% Initialize n to 2
n = 2;
% Compute h for current value of n
h = (b - a)/n;
% Calculate initial value of integral using equation 4
I = (h/3)*( f(a) + 4*f((a+b)/2) + f(b) );
% Start loop - since we don't know the number of steps so we are using
% while loop
while(1)
% Iold saves the current integral value
Iold = I;
% Double the n
n = 2*n;
% Compute h for current value of n
h = (b - a)/n;
% Start calculating integral for current n by equation 5
% We add f values so we sum f(a) and f(b) and store in I
I = f(a) + f(b);
% We add values under first summation sign to I
for j = 1:(n/2-1)
I = I + 2*f(a + 2*j*h);
end
% We add values under second summation sign to I
for j = 1:(n/2)
I = I + 4*f(a + (2*j-1)*h);
end
% We multiply h/3 to final sum
I = I*h/3;
% If stopping condition is satisfied then stop
if abs((I-Iold)/Iold) <= tol
break;
end
end
end