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

9 visualizzazioni (ultimi 30 giorni)
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 Commenti
Guillaume
Guillaume il 8 Lug 2019
filter can't be used for that and I doubt there's anything faster than a loop.
Jan
Jan il 8 Lug 2019
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.

Accedi per commentare.

Risposta accettata

Guillaume
Guillaume il 5 Lug 2019
Modificato: Guillaume il 5 Lug 2019
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 Commenti
Guillaume
Guillaume il 5 Lug 2019
Turns out that filter is actually about 3 times slower than a loop (R2019a)
Jan
Jan il 8 Lug 2019
Modificato: Jan il 8 Lug 2019
@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.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by