How to speed up my code and improve/avoid for loop
显示 更早的评论
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 个评论
per isakson
2017-10-12
Given i is a scalar, what is
eTG(i(eTG(i)>0))=0
supposed to do?
Sergei Zhuravlev
2017-10-12
编辑:Sergei Zhuravlev
2017-10-12
Walter Roberson
2017-10-12
Replace that with
eTG(i) = max(0, eTG(i));
Could you confirm that you want negative values to be left untouched, but positive values to be set to 0?
Sergei Zhuravlev
2017-10-12
编辑:Sergei Zhuravlev
2017-10-12
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
2017-10-12
编辑:Sergei Zhuravlev
2017-10-12
类别
在 帮助中心 和 File Exchange 中查找有关 Parallel Computing Toolbox 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!