# Help with numerical integral

1 vue (au cours des 30 derniers jours)
PTK le 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);
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponses (1)

Davide Masiello le 25 Jan 2023
Modifié(e) : Davide Masiello le 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).
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by