MATLAB Part 2: Numerical Integral Save your file as integral.m Create a function
ID: 3712406 • Letter: M
Question
MATLAB
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.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.