I just tried to replace "for" with "parfor", and there was 50 % time dedutction. I may still need to change trapz with sum.
How do I replace trapz with sum?
5 次查看(过去 30 天)
显示 更早的评论
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;
采纳的回答
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 个评论
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 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!