Help with numerical integral

5 Ansichten (letzte 30 Tage)
PTK
PTK am 25 Jan. 2023
Bearbeitet: Davide Masiello am 25 Jan. 2023
Hello everyone, I wrote this code to calculate the integral using the trapezoidal method, the code is correct. But now I want to plot a graph of this function where the x-axis I need to have h... how can I create parameter h using multiplication of 2... for example h is (b-a)/n, my next h is 2* h, next 4*h, next 6*, and so on. Can you help me with this?
clear all;
close all;
clc
e=0.1;
f=@(x)exp(x)./(1+x);
a=0.5;
b=1.1;
n=2;
h=(b-a)/n;
i=1:1:n-1;
S=f(a+i.*h);
tt = (h./2).*(f(a)+2.*sum(S)+f(b));
fprintf('The value of integration is %f\n', tt);

Antworten (1)

Davide Masiello
Davide Masiello am 25 Jan. 2023
Bearbeitet: Davide Masiello am 25 Jan. 2023
I guess this is what you're looking for
e=0.1;
f=@(x)exp(x)./(1+x);
a=0.5;
b=1.1;
n=2;
h=(b-a)/n;
i=1:1:n-1;
S=f(a+i.*h);
tt = (h./2).*(f(a)+2.*sum(S)+f(b));
fprintf('The value of integration is %f\n', tt);
The value of integration is 0.750379
hx = 0:2:n;
x = a+h*hx;
plot(hx,f(x),'-o')
xlabel('h')
ylabel('f(x)')
Of course it is a straight line here because you x goes only to 2*h.
if you increase the number of interval you'd get something like this
e=0.1;
f=@(x)exp(x)./(1+x);
a=0.5;
b=1.1;
n=20;
h=(b-a)/n;
i=1:1:n-1;
S=f(a+i.*h);
tt = (h./2).*(f(a)+2.*sum(S)+f(b));
fprintf('The value of integration is %f\n', tt);
The value of integration is 0.747541
hx = 0:2:n;
x = a+h*hx;
plot(hx,f(x),'-o')
xlabel('h')
ylabel('f(x)')
You may notice that the value of the integral has also changed (it is more accurate now).

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by