a question on for loop statement

3 ビュー (過去 30 日間)
ektor
ektor 2019 年 5 月 16 日
コメント済み: Luna 2019 年 5 月 17 日
Dear all,
I have this for loop
T=1000;
k=0.1;
u=rand(T,1);
a = zeros(T,1);
a(1) =u(1)+ k*0.01;
for t=2:T
a(t) = u(t,1) + k*a(t-1);
end
Is there a faster way of obtaining a? Maybe if I avoid loop?
  4 件のコメント
Adam Danz
Adam Danz 2019 年 5 月 16 日
編集済み: Adam Danz 2019 年 5 月 16 日
This is the tricky part: *a(t-1)
Short answer to "is there a faster way": Probably not.
There's probably a way to avoid the loop by replacing it with a convoluted, unreadable, jumble of functions but I doubt it will be as fast and it will not be as intuitive. If your loop works for you, keep it. It's simple, clean, and fast.
Luna
Luna 2019 年 5 月 16 日
I agree with Adam I have tried with both T = 1000 and T = 1000000.
The time perfomances are below:
T = 1000 -> Elapsed time is 0.051244 seconds.
T = 1000000 -> Elapsed time is 0.073614 seconds.
The for loop is already as fast as it could be and the simplest solution.

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

回答 (1 件)

Jos (10584)
Jos (10584) 2019 年 5 月 16 日
This is filtering.
T=10; % smaller example
k=0.1;
u=rand(T,1);
% your loop -> a
a = zeros(T,1);
a(1) =u(1)+ k*0.01; % i do not get this addition ...
for t=2:T
a(t) = u(t,1) + k*a(t-1);
end
% filtering -> aa
uu = u ;
uu(1) = uu(1) + k*0.01 ; % implement offset?
aa = filter(1, [1 -k], uu) ;
% do they produce the same result?
isequal(a, aa) % YES
  9 件のコメント
Jos (10584)
Jos (10584) 2019 年 5 月 17 日
btw, regarding execution time, you should also include the pre-allocation of the array :-D
Luna
Luna 2019 年 5 月 17 日
+1 Jos :)

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

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by