필터 지우기
필터 지우기

Problem in generating iterations in 3/8 simpson rule

조회 수: 4 (최근 30일)
Ipshita
Ipshita 2020년 12월 5일
댓글: Ipshita 2020년 12월 6일
I want to make simpson rule algorithm for my function for different intervals (here, 3^p), and plot the error vs p. The code below is showing error in the use of syms in 1st line and the iteration of line 9 (Itr=Itr+f(N+1)/2). Please tell what is wrong in this and how can I correct it.
syms p
N=3^p;
h=1/N;
for i=1,N;
x=i*h;
f(i)=exp(-x^2)
Itr=f(1)/2;
Itr=Itr+(3/2)*f(i);
Itr=Itr+f(N+1)/2;
end
Itr=Itr*h;
for p=1,10;
plot(p,itr)
end
Error using sym/subsindex (line 857)
Invalid indexing or function definition. Indexing must follow MATLAB indexing. Function arguments must be symbolic variables, and function body must be sym expression.
Error in sym/subsref (line 902)
R_tilde = builtin('subsref',L_tilde,Idx);
Error in simpson3by8rule (line 9)
Itr=Itr+f(N+1)/2;

채택된 답변

Alan Stevens
Alan Stevens 2020년 12월 5일
편집: Alan Stevens 2020년 12월 5일
Not entirely clear to me between what limits you are integrating, nor what your loops are doing! Perhaps the following might help:
% Integrate exp(-x^2) from x = 0 to x = 3 using Simpson's 3/8 rule
% I = 3*h/8*(f(a))+sum(f(i)+f(i+1),i=2:3:n-2)+sum(f(i),i=3:3:n-1)+f(b))
f = @(x) exp(-x.^2); % function
a = 0; % lower limit
b = 3; % upper limit
n = 333; % number of panels (multiple of 3)
h = (b - a)/n; % panel size
x = a:h:b; % vector of x values
s3 = 0;
for j = 2:3:n-2
s3 = s3 + f(x(j)) + f(x(j+1));
end
s2 = 0;
for j = 3:3:n-1
s2 = s2 + f(x(j));
end
I = 3*h/8*(f(a) + 3*s3 + 2*s2 + f(b));
disp('Approximate integral of exp(-x^2) from x=0 to x=3 using')
disp(['Simpson''s 3/8 rule with ' int2str(n) ' panels is: ' num2str(I,4)])
Modify to suit exactly what you want.
  댓글 수: 8
Alan Stevens
Alan Stevens 2020년 12월 6일
편집: Alan Stevens 2020년 12월 6일
In
estimateerror(x)=-3*df4(x)*h^5/80
the first value of x is 0, but indices in Matlab start at 1 not 0. Try replacing it with
for i = 1:numel(x);
estimateerror(i)=-3*df4(x(i))*h^5/80;
end
(Matlab would also not like other values of x that were not integers being used as indices).
Ipshita
Ipshita 2020년 12월 6일
Thanks a lot, it worked!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with Symbolic Math Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by