フィルターのクリア

Speeding up a loop

2 ビュー (過去 30 日間)
Swisslog
Swisslog 2013 年 1 月 17 日
I have made a simple loop that works fine when dealing with small datasets, but takes ages to run when L is 10^6 in size - which unfortunately is the size I need to work with. I'm sure you can tell by the code itself I'm a matlab newbie, so any ideas on how this can be sped up would be very much appreciated. I've read about vectorisation but cannot work out how to vectorise this code.
C=cumsum(S);
L=length(C);
X=zeros(1,L)';
for i=1:L;
if C(i)>min(C(i:L));
X(i);
else
X(i)=1;
end
end
  4 件のコメント
Swisslog
Swisslog 2013 年 1 月 17 日
編集済み: Swisslog 2013 年 1 月 17 日
Hi Rick,
I'm dealing with column vectors. I have a column of random numbers (S), which I add up C=(cumsum(S). I want to identify from C intervals where C is increasing (marked as 1 in X), and intervals where it is decreasing (marked as 0 in X). Importantly, if C is decreasing, I also want to set to 0 those values immediately before the decrease which are greater than the minimum value attained during the suceeding decrease - hence: if C(i)>min(C(i:L)). The code works precisely as I want it to, but just takes forever (~1 hour) when Length(S)=10^6.
P.S. As a slight aside, in the parlance of fractals: the aim of this code is esentially to construct a 1D cantor set (X) from a random series (S). In this sense C is akin to a devils staircase
Jan
Jan 2013 年 1 月 17 日
Is the wanted property of C directly related to the sign of the corresponding element of S?

サインインしてコメントする。

採用された回答

Jan
Jan 2013 年 1 月 17 日
編集済み: Jan 2013 年 1 月 17 日
The main work is done in the repeated determination of the minimum. But this can be avoided easily:
% Cummumaltive minimum in backward direktion:
minC = zeros(size(C));
v = C(end);
for ii = numel(C):-1:1
if C(ii) < v
v = C(ii);
end
minC(ii) = v;
end
X = zeros(L, 1);
X(C <= minC) = 1;
Sorry, I cannot test this currently and I have the feeling that the logic is not correct. But at least the general idea could be helpful.
Btw.: This line wastes time only:
X(i);

その他の回答 (1 件)

Swisslog
Swisslog 2013 年 1 月 17 日
Thanks Jan, This seems to have done the trick - much faster and I've learned a lot, cheers

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by