MATLAB Answers

Help with writing a code for computing the area under a curve.

14 views (last 30 days)
Jeff Smith
Jeff Smith on 5 Apr 2018
Commented: John D'Errico on 5 Apr 2018
I need to write a MATLAB function called Area1 having two inputs, r and N, and an output, A1. The output A1 should be the area under a curve, f(x), for x starting at start_x and ending at end_x. The input r should be a vector having start_x and end_x as its two elements. The input N should be an integer equal to the number of equal-length sub-intervals in which the interval from start_x to end_x should be divided.
First, I need to use function: f(x) = 0.1x^2+ cos(0.4 π x) +exp(-x^2/10) for start_x = 0 and end_x = 10. In other words, the Area1.m file which includes the function should look as follows:
function A1 = Area1(r, N)
"the code"
First, do the mid point approximation. Next do the same thing, but use Area2 as the trapezoid method.
Create another script (e.g., main.m) and call A1 = Area1(r, N); and A2 = Area2(r, N); within a for loop which increases N from 5 to 50 with step of 1. Save the 46 results into vectors A_all1 and A_all2. Then plot A_all1 and A_all2 with respect to the 46 corresponding values of N in a single plot, and observe how they converge to the true area as N increases. Add appropriate xlabel and ylabel. Which method converges faster?
I'm not really sure where to begin with this, so any input helps. Thanks.

Answers (1)

CARLOS RIASCOS on 5 Apr 2018
Hello brother, I hope that my code can help you, it is the trapezoidal method defined in the attached image.
function A1 = Area1(n,r)
a = r(1); %star x
b = r(2); %end x
h = (b-a)/n;
%You could modify this function at your whim, consult about the handle
f = @(x) (0.1*x^2 + cos(0.4*pi*x) + exp(-x^(2/10)));
yo = f(a);
yn = f(b);
beta = 0; %auxiliary var.
for i = 1:(n-1) %Sum defined by the trapezoidal method.
beta = beta + f(a+h*i);
A1 = (h/2)*(yo + yn +2*beta);
John D'Errico
John D'Errico on 5 Apr 2018
Hi. We try not to do people's homework for them on this site. It does not help them, and only convinces them they can always get someone else to do their work for them.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!