我刚刚开始学习MATLAB。 练习的目的是使用Simpson的1/3规则和romberg进行近似/整合。问题是将x ^(1/2)从0整合到2
执行时:simpson(fun,0,2,10)
我在第2行收到错误:fun = x^(1/2);
或者在辛普森的第16行:f = feval(fun,x);
感谢您的帮助!
这是我的公式代码:
function [fun] = ff(x)
fun = x^(1/2);
end
我的辛普森代码:
function I = simpson(fun,a,b,npanel)
% Multiple Segment Simpson's rule
%
% Synopsis: I = simpson(fun,a,b,npanel)
%
% Input: fun = (string) name of m-file that evaluates f(x)
% a, b = lower and upper limits of the integral
% npanel = number of panels to use in the integration
% Total number of nodes = 2*npanel + 1
%
% Output: I = approximate value of the integral from a to b of f(x)*dx
n = 2*npanel + 1; % total number of nodes
h = (b-a)/(n-1); % stepsize
x = a:h:b; % divide the interval
f = feval(fun,x); % evaluate integrand
I = (h/3)*( f(1) + 4*sum(f(2:2:n-1)) + 2*sum(f(3:2:n-2)) + f(n) );
% f(a) f_even f_odd f(b)
我的romberg代码:
function [R,quad,err,h]=romberg(fun,a,b,n,tol)
%Input - fun is the integrand input as a string 'fun'
% - a and b are upper and lower limits of integration
% - n is the maximum number of rows in the table
% - tol is the tolerance
%Output - R is the Romberg table
% - quad is the quadrature value
% - err is the error estimate
% - h is the smallest step size used
M=1;
h=b-a;
err=1;
J=0;
R=zeros(4,4);
R(1,1)=h*(feval(fun,a)+feval(fun,b))/2;
while((err>tol)&(J<n))|(J<4)
J=J+1;
h=h/2;
s=0;
for p=1:M
x=a+h*(2*p-1);
s=s+feval(fun,x);
end
R(J+1,1)=R(J,1)/2+h*s;
M=2*M;
for K=1:J
R(J+1,K+1)=R(J+1,K)+(R(J+1,K)-R(J,K))/(4^K-1);
end
err=abs(R(J,J)-R(J+1,K+1));
end
quad=R(J+1,J+1);