我已经为辛普森 1/3 规则编写了一个 matlab 代码。我为它做了一个函数然后我在程序中调用它

I've written a matlab code for simpson 1/3 rule. I made a function for it and then i'm calling it in program

这是辛普森函数

%Simpsons 1/3 rule

function y = simpson(f,x1,x2,n)
global h
%global x1
%global x2
%h = (x2-x1)/n;
x(1) = x1;
sum = f(x1);
for i=2:n+1
    x(i)=x(i-1)+h;
    if mod(i,2)==0
        sum=sum+4*f(x(i));
    else
        sum=sum+2*f(x(i));
    end
end

sum = sum + f(x2);
int = sum*h/3;
disp(int);
end

这是我要调用的代码:

CAo = 0.0625;
x1=0;
x2=0.8;
h=0.2;
n=(x2-x1)/h;
ep=2;
f=inline('(1+2*x)/((1-x)*0.0625)');
y = simpson(f,x1,x1,n);
disp(y)

在 运行 代码上,它给出了这个错误:

In an assignment  A(I) = B, the number
of elements in B and I must be the
same.

Error in simpson (line 12)
    x(i)=x(i-1)+h;

Error in tut_4_1 (line 8)
y = simpson(f,x1,x1,n);

我试过调试,它显示我的h是0,我的x(i-1)是1X1。如何解决这个问题。 ?

问题出在下面这行代码:

global h;

这涉及h的范围。 global 关键字仅在函数的 生命周期 期间影响变量 h。如果在命令 window 中设置 h,然后尝试 运行 Simpson 规则,h 的范围与函数本身中看到的不同。事实上,文件中的变量 h 与命令 window.

中看到的 NOT 相同

你的函数也有错误。您正在返回 y,但输出存储在 int 中。您需要将其更改为 y.

因此,您可以通过两种方式解决此问题:

  1. 将调用辛普森法则的实际代码放在一个函数中,并将辛普森法则代码本身作为一个嵌套函数。您需要删除对 global h 的调用并将其放置在辛普森规则代码的 外部 之外。像这样:

function [] = test_simpsons()

global h;

    function y = simpson(f,x1,x2,n)

    x(1) = x1;
    sum = f(x1);
    for i=2:n+1
        x(i)=x(i-1)+h;
        if mod(i,2)==0
            sum=sum+4*f(x(i));
        else
            sum=sum+2*f(x(i));
        end
    end

    sum = sum + f(x2);
    y = sum*h/3;
    end

CAo = 0.0625;
x1=0;
x2=0.8;
h=0.2;
n=(x2-x1)/h;
ep=2;
f=inline('(1+2*x)/((1-x)*0.0625)');
y = simpson(f,x1,x1,n);
disp(y);

end

然后您将调用 test_simpsons

  1. 这是我推荐的方法。只需将 h 作为您的辛普森规则代码的 输入参数

%Simpsons 1/3 rule

function y = simpson(f,x1,x2,n,h)
x(1) = x1;
sum = f(x1);
for i=2:n+1
    x(i)=x(i-1)+h;
    if mod(i,2)==0
        sum=sum+4*f(x(i));
    else
        sum=sum+2*f(x(i));
    end
end

sum = sum + f(x2);
y = sum*h/3;
end

您现在调用测试代码的方式是:

CAo = 0.0625;
x1=0;
x2=0.8;
h=0.2;
n=(x2-x1)/h;
ep=2;
f=inline('(1+2*x)/((1-x)*0.0625)');
y = simpson(f,x1,x1,n,h);
disp(y)