create a vector whose elements depend on its previous elements without a loop

7 ビュー (過去 30 日間)
Galgool
Galgool 2019 年 7 月 5 日
コメント済み: Jan 2019 年 7 月 8 日
Hi,
As loops take considerable time, I'm trying without loops.
I want to create a vector whose elements depend on its previous elements, for example:
a(i) = 3*a(i-1) + 2
a(1) = 5
where a(i) is the i-th value of vector A.
Can it be done?
  6 件のコメント
Guillaume
Guillaume 2019 年 7 月 8 日
filter can't be used for that and I doubt there's anything faster than a loop.
Jan
Jan 2019 年 7 月 8 日
This might be 10% faster than fillwithfilter:
function a = fillwithfilter2(nelem)
q = zeros(1, nelem);
q(1) = 5;
q(2:nelem) = 10;
a = filter(1, [1, -3], q);
end
But this is of academic interest only, if the loop is much faster.

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

採用された回答

Guillaume
Guillaume 2019 年 7 月 5 日
編集済み: Guillaume 2019 年 7 月 5 日
Doing this will a loop shouldn't be slow as long as you preallocate the array beforehand:
a = zeros(1, 100); %preallocation
a(1) = 5;
for i = 2:numel(a)
a(i) = 3 * a(i-1) + 2;
end
It can indeed be done without a loop, with the filter function, the most difficult is to figure out the inputs. The more about section is the most helpful.
a = filter(1, [1 -3], [5, 2*ones(1, 99)]); % 1*y(n) = 1*x(n) - (-3)*y(n-1), with x = [5, 2, 2, ...] and y(0) = 0
Frankly, the loop is clearer so you should prefer it.
  4 件のコメント
Guillaume
Guillaume 2019 年 7 月 5 日
Turns out that filter is actually about 3 times slower than a loop (R2019a)
Jan
Jan 2019 年 7 月 8 日
編集済み: Jan 2019 年 7 月 8 日
@Guillaume: Even if we do something wrong (a kind of pre-mature optimization), CPUs are deterministic machines and an arithmetic operation, which needs less cycles, should consume less time.
x = ones(1, 1e6);
timeit(@() x * 2) % 1.2651e-04
timeit(@() x + 1) % 1.2923e-04
By the way, the timings are equivalent for x * 2.22 and x + 2.22, so this is not a magic effect of the JIT performing some smart repelacement for the multiplication by 2.
Nevertheless, this does not concern the question of this thread. I'm going to discuss this somewhere else.

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by