Filter löschen
Filter löschen

Composite Simpson's 1/3 rule code error

1 Ansicht (letzte 30 Tage)
Maria Galle
Maria Galle am 21 Nov. 2020
Beantwortet: Steve Areola am 5 Aug. 2023
I'm trying to use the composite simpsons 1/3 rule but the code is giving me an error message.
fx=1-exp(-x);
n = 5;
x = linspace(0, 4,1000);
h = (x(end) - x(1))/n; % width of each segment
x_simp = linspace(0, 4, n+1);
for k = 1:n
x_simp_begin(k) = x_simp(k);
x_simp_end(k) = x_simp(k+1);
x_simp_mid(k) = (x_simp_begin(k) + x_simp_end(k))/2;
fx_simp_begin(k) = fx(x_simp_begin(k));
fx_simp_end(k) = fx(x_simp_end(k));
fx_simp_mid(k) = fx(x_simp_mid(k));
I_simp_seg(k) = h/6*(fx_simp_begin(k) + 4*fx_simp_mid(k) + fx_simp_end(k));
end
I_simp = sum(I_simp_seg)
Error message:
Array indices must be positive integers or logical values.

Antworten (2)

John D'Errico
John D'Errico am 21 Nov. 2020
Tell me, what is fx?
fx is NOT a function. It is a scalar, vector, or array. Whatever x was, fx is the same thing. If it NOT a function that you can evaluate at some point. So then, when you write
I_simp_seg = 1/6*(fx(0) + 4*fx(mid) + fx(4));
what does MATLAB do? It KNOWs that fx is a variable. It tries to index the variable at position 0. What did it tell you?
Array indices must be positive integers or logical values.
You need to learn how to write a FUNCTION that can be passed arguments. You MIGHT try a function handle.
doc function_handle
A simple example for your problem here would be
fx = @(x) 1-exp(-x);

Steve Areola
Steve Areola am 5 Aug. 2023
clc
a=0;b=2;n=8;
h=(b-a)/n;
f=@(x) exp(2*x)*sin(3*x);
XI0= f(a) +f(b);
XI1 = 0;
XI2 = 0;
for i = 1:n-1
x = a+i*h;
if mod(i,2)==0
XI2=XI2 + f(x);
else
XI1 = XI1 + f(x);
end
end
XI=(h/3)*(XI0+2*XI2+4*XI1);
fprintf("the approximation of the integral is equal to %0.9f",XI)

Kategorien

Mehr zu Numerical Integration and Differential Equations 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