Composite Simpson's 1/3 rule code error

8 ビュー (過去 30 日間)
Maria Galle
Maria Galle 2020 年 11 月 21 日
回答済み: Steve Areola 2023 年 8 月 5 日
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.

回答 (2 件)

John D'Errico
John D'Errico 2020 年 11 月 21 日
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 2023 年 8 月 5 日
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)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by