Matlab 中的 Simpson's 1-3 (h / 3) 方法

问题描述

下面给出了根据辛普森 1-3 (h / 3) 方法求出下列积分的 C 代码。适当填写代码上的空白。 我想在 Matlab 中解决下面的这个问题,但我没有这样做。这是一个简单的问题,但我做不到。如果有人帮助我,我会很高兴。

C code version

[C 代码版本2

我在 Matlab 中尝试了这个代码块:

% Ask for user input
% Lower bound (a)
a = input('What is your lower bound (a)?')
% Upper bound (b)
b = input('What is your upper bound (b)?')
% Subintervals
N = input('How many subintervals (N)?')
% Defining function
f = @(x,e) (e*x+sin(x))
% Finding h
h=(b-a)/N; 
% Finding the values of x for each interval
x=linspace(a,b,N);
% Calculating the integral
for i = 1:N-1
I(i)= (h/3)*(f(x(i))+(4*f((x(i)+x(i+1))/2))+f(x(i+1)));
end
answer1 = sum(I)
disp(I)
% adding f(b) to sum
val2=ff(length(xx));
sum=val1+val2+sum;% set sum
% set result
result=sum*h/3;

解决方法

请注意,MATLAB 不使用符号 e 作为 Neperian Number(欧拉数)。要在 MATLAB 中生成欧拉数,您可以使用指数函数 exp(x),e = exp(1),

因此,首先,更正您的函数定义:

F = @(x) exp(1).^x + sin(x)  % Always try to use Upper-Case letters for your variable/function name

然后,您可以使用以下代码段使用辛普森的 1/3 计算积分:

a = 0; b = 3; N = 1e4;

F = @(x) exp(1).^x + sin(x);

h = ((b-a)/2)/N; 
x = linspace(a,b,N);

I = 0;
for i = 1:N-1
    I = I + h/3*(F(x(i)) + 4*F((x(i)+x(i+1))/2) + F(x(i+1)));
end

disp(I)
% To compare your result:
Itz = trapz(x,F(x))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...