MATLAB: How to replace trapz with sum

trapz

Hi My Matlab is R2016b version, and below is a part of code I am struggling with.
I want to change trapz parts into sum to speed up the calculation.
Can you help me?
elseif fit_method == 2
tic;
N=length(xy(:,2));
N=N-1;
dt = 10^-8;
SY = 0;
t_SY = 0;
Y_SY = 0;
SY_SY = 0;
Y_t = 0;
for M = 2:N
SY_comp = trapz(xy(1:M,1),xy(1:M,2));
SY = SY+SY_comp;
t_SY_comp = M*trapz(xy(1:M,1),xy(1:M,2));
t_SY = t_SY + t_SY_comp;
Y_SY_comp = xy(M,2)*trapz(xy(1:M,1),xy(1:M,2));
Y_SY = Y_SY + Y_SY_comp;
SY_SY_comp = (trapz(xy(1:M,1),xy(1:M,2)))^2;
SY_SY = SY_SY + SY_SY_comp;
Y_t_comp = xy(M,2)*M;
Y_t = Y_t + Y_t_comp;
end;
Y = sum(xy(1:N,2));
t = N*(N+1)/2;
t_t = N*(N+1)*(2*N+1)/6;
A = double([N, SY, t; SY, SY_SY, Y_SY; t, t_SY, t_t]);
B = double([Y;Y_SY;Y_t]);
X = inv(A)*B;
tau = dt/log(1-X(2,1)*dt);
fit_success = 0;
toc;

Best Answer

In place of “SY_comp=trapz(xy(1:M,1),xy(1:M,2))” you could write:
SY_comp=1/2*sum(diff(xy(:,1)).*(xy(1:M-1,2)+xy*(2:M,2)));
However, I seriously doubt that this will speed up the calculation. There is no particular reason to assume that Mathworks’ ‘sum’ function is any more efficient than the ‘trapz’ function.