Filter löschen
Filter löschen

Problem in generating iterations in 3/8 simpson rule

4 Ansichten (letzte 30 Tage)
Ipshita
Ipshita am 5 Dez. 2020
Kommentiert: Ipshita am 6 Dez. 2020
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;

Akzeptierte Antwort

Alan Stevens
Alan Stevens am 5 Dez. 2020
Bearbeitet: Alan Stevens am 5 Dez. 2020
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 Kommentare
Alan Stevens
Alan Stevens am 6 Dez. 2020
Bearbeitet: Alan Stevens am 6 Dez. 2020
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 am 6 Dez. 2020
Thanks a lot, it worked!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Get Started with Symbolic Math Toolbox 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