Integration approximation with function handle

17 次查看(过去 30 天)
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 个)

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