How to plot results from Simpson's Rule integration?

조회 수: 43(최근 30일)
Hi All,
I am currently trying to do some integration using the Simpson's rule. My codes does produce the required approximation. But I don't understand how I can obtain a plot of the number of panels (x-axis) vs the integral evaluated at each panel (y-axis). My code uses 10 panels. The plot should be some what of a zig zag in appearance. Could someone please provide some assistance regarding this matter?
My code is shown below:
%Function to be integrated
f=@(x)exp(x);
%lower limit
a=0;
%upper limit
b=1;
%number of panels
n=10;
%interval size
h=(b-a)/n;
%summation of first two values
s=f(a)+f(b);
%loop for the rest of the calculations
for i=1:2:n-1
s=s+4*f(a+i*h); %summation
end
for i=2:2:n-2
s=s+2*f(a+i*h); %summation
end
%evaluate integral
I=h/3*s

채택된 답변

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam 2020년 10월 15일
function ask005
%Function to be integrated
f=@(x)exp(x);
%lower limit
a=0;
%upper limit
b=1;
N=[10, 20, 40, 100, 200, 400, 800, 1000];
In = NaN(size(N));
%number of panels
for j = 1:length(N)
%interval size
n=N(j);
h=(b-a)/n;
%summation of first two values
s=f(a)+f(b);
%loop for the rest of the calculations
for i=1:2:n-1
s=s+4*f(a+i*h); %summation
end
for i=2:2:n-2
s=s+2*f(a+i*h); %summation
end
%evaluate integral
I=h/3*s;
In(j) = I;
end
% plot(N,In);
% or
semilogx(N,In);
end
  댓글 수: 1
JoBrr
JoBrr 2020년 10월 15일
Thanks for the help Asad, after a brief modification of your code I managed to get the correct result for my purpose.

댓글을 달려면 로그인하십시오.

추가 답변(0개)

범주

Find more on Symbolic Math Toolbox in Help Center and File Exchange

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by