Integration approximation with function handle

조회 수: 19 (최근 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 CenterFile Exchange에서 Numerical 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