MATLAB Simpson's 1/3 Rule and Romberg

会有一股神秘感。 提交于 2020-02-08 06:17:12

问题


I'm just starting to learn MATLAB. The purpose of the exercise is to approximate/integrate using Simpson's 1/3 rule and romberg. The problem is to integrate x^(1/2) from 0 to 2

When I execute: simpson(fun,0,2,10)

I get an error on line 2: fun = x^(1/2); or on line 16 of simpson: f = feval(fun,x);

Thanks for the help!

Here is my equation code:

function [fun] = ff(x)
    fun = x^(1/2);
end

My simpson code:

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)

My romberg code:

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);

来源:https://stackoverflow.com/questions/44908174/matlab-simpsons-1-3-rule-and-romberg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!