Help with numerical integral

조회 수: 1 (최근 30일)
PTK
PTK 2023년 1월 25일
편집: Davide Masiello 2023년 1월 25일
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);

답변 (1개)

Davide Masiello
Davide Masiello 2023년 1월 25일
편집: Davide Masiello 2023년 1월 25일
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).

카테고리

Help CenterFile Exchange에서 Assembly에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by