How to speed up my code and improve/avoid for loop

조회 수: 12 (최근 30일)
Sergei Zhuravlev
Sergei Zhuravlev 2017년 10월 12일
편집: Sergei Zhuravlev 2017년 10월 12일
Dear all, that's my piece of code that works correctly but too slow.
T=rand(100000,1)-0.3;
eTG=zeros(size(T)); %set eTG(1)=0 and preallocate
for i=2:length(T)
eTG(i)=eTG(i-1)+T(i-1);
eTG(i(eTG(i)>0))=0;
end
Preallocation doesn't help and "run and time" tool shows that string
eTG(i(eTG(i)>0))=0;
eats 83% of the total time. Please give me your advices how to optimize this code. Are there any ways to vectorize this code and avoid loops at all?
  댓글 수: 5
Sergei Zhuravlev
Sergei Zhuravlev 2017년 10월 12일
편집: Sergei Zhuravlev 2017년 10월 12일
Yes, exactly. Using max function gives wrong results, Should be "min" I suppose. Thank you!
Walter Roberson
Walter Roberson 2017년 10월 12일
Dang, I got it wrong this time too. Yes, min(0, eTG(i)) if you want negative untouched and positive set to 0.

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

답변 (1개)

Sergei Zhuravlev
Sergei Zhuravlev 2017년 10월 12일
편집: Sergei Zhuravlev 2017년 10월 12일
This code is 10 times faster (thanks to Walter Roberson)
T=rand(100000,1)-0.3;
eTG=zeros(size(T)); %set eTG(1)=0 and preallocate
for i=2:length(T)
eTG(i)=eTG(i-1)+T(i-1);
eTG(i) = min(0, eTG(i));
end

카테고리

Help CenterFile Exchange에서 Parallel Computing Toolbox에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by