Part 2: Numerical Integral Save your file as integral.m Create a function with t
ID: 2291926 • Letter: P
Question
Part 2: Numerical Integral Save your file as integral.m Create a function with the headerline function integral(x, y) Where x and y are vectors and x has a step size of h Your function should numerically estimate the integral from a to b of y (where a is the first value in the x-vector and b is the last value) using the following methods: Rectangular using the left hand value Rectangular using the right hand value -Trapezoidal You may not use any of MATLAB's built in functions for integrals, but you may use the sum() function If x is a vector, sum(x) will sum all of the entries in the vector. Your function should print out your solutions using the lines of code fprintf(['n the integral using the left Riemann sum is num2str(left)]) fprintf(['n the integral using the right Riemann sum is num2str(right)]) fprintf(['n the integral using the trapezoid sum is ' num2str(trap) 'In'1) Test vour function: yexp(-x.2); >> integral(x,y); the integral using the left Riemann sum is 0.83623 the integral using the right Riemann sum is 0.93623 the integral using the trapezoid sum is 0.88623Explanation / Answer
clc
clear all
close all
x=-5:0.01:0;
f=@(x) exp(-x.^2);
a=min(x);
b=max(x);
n=length(x);
r=integral1(f,a,b,n);
fprintf(' The integral using the left Riemann sum is: %f ', r)
r=integralR(f,a,b,n);
fprintf(' The integral using the right Riemann sum is: %f ', r)
r=trapezoid(f,a,b,n);
fprintf(' The integral using the trapezoid sum is: %f ', r)
function r=integral1(f,a,b,n)
dx=(b-a)/n;
r=f(a);
for k=1:n-1
c=a+k*dx;
r=r+f(c);
end
r=dx*r;
end
-----------------------
function r=integralR(f,a,b,n)
r = 0;
dx = (b-a)/n;
for k=1:n
c = a+k*dx;
r = r + f(c);
end
r = dx*r;
------------
function r=trapezoid(f,a,b,n)
x=a:0.01:b;
dx = x(2) - x(1);
f = exp(-x.^2);
r=(sum(f)-(f(1)+f(end))/2)*dx;
Output:
The integral using the left Riemann sum is: 0.881237
The integral using the right Riemann sum is: 0.891217
The integral using the trapezoid sum is: 0.886227