ff=input('function:','s'); %注意乘与点乘,要用点乘,如exp(-x/4).*cos(x)
fun=eval(['@(x)',ff]);
x0=input('x0:');
x1=input('x1:');
n=input('n:'); %偶数
h=(x1-x0)/n;
x=x0:h:x1; x=x(:)';
y=fun(x);
f=[2*ones(1,n/2+1);4*ones(1,n/2+1)]; f=f(:)'; f(1)=1; f(end)=[]; f(end)=1;
%数值积分
Int=h/3*sum(f.*y);
xx=repmat(x(:)',2,1); xx=xx(2:end); xx=xx(:);
yy=repmat(y(:)',2,1); yy=yy(1:end-1); yy=yy(:);
plot(x,y,'k')
hold on
plot(xx,yy,'r');
plot(repmat(x(1:2:end),2,1),[zeros(size(x(1:2:end)));y(1:2:end)],'b')
plot(repmat(x(2:2:end),2,1),[zeros(size(x(2:2:end)));y(2:2:end)],'g')
plot([x0,x1],[0,0],'k');
xlabel('X')
ylabel('Y')
title(['Numeric integration of ',ff,' with ',num2str(n),' slices'])
vpa(Int,10) %数值解
%%下面是符号解
vpa(int(sym(strrep(strrep(ff,'.*','*'),'./','/')),x0,x1),10)
温馨提示:答案为网友推荐,仅供参考