Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

MATLAB Part 2: Numerical Integral Save your file as integral.m Create a function

ID: 3712406 • Letter: M

Question

MATLAB

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(I'In the integral using the left Riemann sum is 'num2str(left)]) fprintf(['In the integral using the right Riemann sum is num2str(right)]) fprintf(I'In the integral using the trapezoid sum is num2str(trap) 'In']) Test your function: >>y exp(-x.A2); >> 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 .88623

Explanation / Answer

x=-5:0.1:0;
y =@(x) exp(-x.^2);

function [left,right,trap] = integral(x,y);
a=min(x); %lower limit of vector
b=max(x); %lower limit of vector
dx=x(2)-x(1); %stepsize
n=(b-a)/dx; %no. of steps
right=0.0;
left=0.0;
trap=0.0;
for i=1:n
right=right+y(a+dx*(i)); %do operation for right reimen
left=left+y(a+dx*(i-1)); %do operation for left reimen
if i==1
trap=trap+0.5*y(a+dx*(i));
elseif i==n-1
trap=trap+0.5*y(a+dx*(i));
else
trap=trap+y(a+dx*(i));
end   
end
right=right*dx;
left=left*dx;
trap=trap*dx;
end

[left,right,trap] = integral(x,y);
fprintf([" the integral using the left reimann sum is %f",num2str(left)])
fprintf([" the integral using the right reimann sum is %f",num2str(right)])
fprintf([" the integral using the trapezoidal sum is %f",num2str(trap)])

Explanation:

1.pass the fuunction and vector x to the function in proper format.

2. First identify the lower and upper limit of the vector and find the step size and num ber of steps.

3. feed these values in iterations and calculate the desired result.