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

조회 수: 3 (최근 30일)
Jeff Smith
Jeff Smith 2018년 4월 5일
댓글: John D'Errico 2018년 4월 5일
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"
end
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.

답변 (1개)

CARLOS RIASCOS
CARLOS RIASCOS 2018년 4월 5일
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
%functions:
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);
end
A1 = (h/2)*(yo + yn +2*beta);
end
  댓글 수: 2
Jeff Smith
Jeff Smith 2018년 4월 5일
편집: Jeff Smith 2018년 4월 5일
Looks great, Thanks! I have this for the midpoint rule. Would you mind checking if I did everything correctly?
function A1 = Area1(r,N)
x_start = r(1);
x_end = r(2);
dx = (x_end-x_start)/N;
f = @(x) (0.1*x.^2+cos(0.4*pi*x)+exp(-x.^2/10));
A1 = sum(f(x_start+dx/2:dx:x_end)*dx);
end
John D'Errico
John D'Errico 2018년 4월 5일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Functional Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by