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

2 ビュー (過去 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 Center および File ExchangeFunctional Programming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by