How do I replace trapz with sum?

조회 수: 6 (최근 30일)
Deo
Deo 2017년 4월 13일
댓글: Roger Stafford 2017년 4월 13일
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
Deo
Deo 2017년 4월 13일
I just tried to replace "for" with "parfor", and there was 50 % time dedutction. I may still need to change trapz with sum.

댓글을 달려면 로그인하십시오.

채택된 답변

Roger Stafford
Roger Stafford 2017년 4월 13일
편집: Roger Stafford 2017년 4월 13일
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
Roger Stafford
Roger Stafford 2017년 4월 13일
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개)

카테고리

Help CenterFile 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