在Matlab中利用trapz函数解决积分问题

cygmwpex  于 2023-01-13  发布在  Matlab
关注(0)|答案(1)|浏览(249)

有人可以帮我解决这个问题。我必须用Matlab的trapz函数计算积分,增加网格间隔N。我需要这样做,直到我达到公差。

N = 1; %Initial number of mesh intervals
    t = [t0,tf]; %Create an initial mesh
    y = L(t); %Evaluate the function at mesh points

    I = trapz(t,y); %Compute the integral numerically using trapz

    epsilon = I;

    while epsilon >= tol % Until I reach tolerance
        
        N = N+1;
        tstep = (tf-t0)/N;
        t1 = t0:tstep:tf;
        y1 = L(t1);
        I_new = trapz(t1,y1); 
        epsilon = I_new - I;
        I = I_new;
       
        
    end

问题是i总是有相同的I_new值,永远不增加.

6vl6ewon

6vl6ewon1#

在epsilon计算中实现一个abs,以避免while循环求值中出现负值。

epsilon = abs(I_new - I);

abs(epsilon) >= tol

还建议将初始epsilon值设置为inf:epsilon = inf;

相关问题