这里是simpson函数
%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。怎么解决这个问题。 ?
答案 0 :(得分:0)
问题是以下代码行:
global h;
这涉及h
的范围。 global
关键字仅影响函数生命周期期间的变量h
。如果在命令窗口中设置h
,然后尝试运行Simpson规则,则h
的范围与函数本身的范围不同。实际上,文件中的变量h
NOT 与命令窗口中的变量相同。
你的功能也有错误。您正在返回y
,但输出存储在int
中。您需要将其更改为y
。
因此,有两种方法可以解决这个问题:
global h
的调用,并将其置于 的Simpson规则代码之外。这样的事情: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
。
h
输入参数添加到您的Simpson规则代码中:%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)