How do I replace trapz with sum?

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;

1 个评论

I just tried to replace "for" with "parfor", and there was 50 % time dedutction. I may still need to change trapz with sum.

请先登录,再进行评论。

 采纳的回答

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.

2 个评论

Deo
Deo 2017-4-13
编辑:Deo 2017-4-13
Because of pre-defined delta value, I used like below. 1/2*sum(dt*(xy(1:M-1,2)+xy(2:M,2))) I just tried to do this because few papers I am refering said that way....and the result was 50 % decrease in process time. Thanks for your help. But I am still desiring to see better idea to reduce processing time. Thanks
If dt is a single scalar value - that is, if all the intervals dt are of the same value - you can use the form
dt*trapz(Y)
instead of
trapz(X,Y)
and that should save time. The equivalent formula using ‘sum’ would be:
dt*((Y(1)+Y(end))/2+sum(Y(2:end-1)));
It is still questionable whether this is faster than trapz(Y).

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Numerical Integration and Differentiation 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by