Integration approximation with function handle

17 ビュー (過去 30 日間)
Mikael Freyhult
Mikael Freyhult 2022 年 6 月 17 日
編集済み: Jan 2022 年 6 月 17 日
Hi, i am having issues with a problem at school.
The assignment is to approximate an integral by(as i understand) looping a function for a set number of times.
Also this function needs to be called upon by a separate script.
I can't get my head around the problem so any help would be gratefully accepted.
The problem:
"" Design a function that approximates integrals with the following formula:
Where h = (b-a)/h. The input parameters must be, a, b, n and an anonymous function (a handle) for f
The only built-in features that can be used are linspace and sum.
Also design a script that calls the function and uses the call to calculate the error
i.e. the (nearest value -the exact value) if a = pi/ 2, b=pi, n=15 and f(x) = xsinx.
The exact the value must be calculated by yourself with partial integration. ""
I have done the hand calculations which results in pi-1
Code1:
I=integralapprox(pi/2,pi,15,@(x) x*sin(x));
E = pi-1;
S = I-E;
Code2:
function I=integralapprox(a,b,n,f0)
h = (b-a)/n;
f = @(a,b,h,f0) ((a+(n-1)*h+a+n*h)/2)*f0;
N=0;
for n=1:n
F = f(a,h,n,f0);
N = N + S;
end
I=h*N;
  1 件のコメント
Torsten
Torsten 2022 年 6 月 17 日
The formula you use to approximate the integral is wrong.

サインインしてコメントする。

回答 (1 件)

Jan
Jan 2022 年 6 月 17 日
編集済み: Jan 2022 年 6 月 17 日
f = @(a,b,h,f0) ((a+(n-1)*h+a+n*h)/2)*f0;
This cannot work if f0 is a function handle.
This is at least confusing:
for n=1:n
Start to write the sum again:
function S = integralapprox(a, b, n, f)
h = (b - a) / n;
S = 0;
for k = 1:n
S = S + f(???); % Use k as index, not n
end
S = h * S;
end

カテゴリ

Help Center および File ExchangeNumerical Integration and Differentiation についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by