# Integration approximation with function handle

1 view (last 30 days)
Mikael Freyhult on 17 Jun 2022
Edited: Jan on 17 Jun 2022
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 CommentShowHide None
Torsten on 17 Jun 2022
The formula you use to approximate the integral is wrong.

Jan on 17 Jun 2022
Edited: Jan on 17 Jun 2022
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

R2021b

### Community Treasure Hunt

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

Start Hunting!