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

7 vues (au cours des 30 derniers jours)
Galgool
Galgool le 5 Juil 2019
Commenté : Jan le 8 Juil 2019
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 commentaires
Guillaume
Guillaume le 8 Juil 2019
filter can't be used for that and I doubt there's anything faster than a loop.
Jan
Jan le 8 Juil 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.

Connectez-vous pour commenter.

Réponse acceptée

Guillaume
Guillaume le 5 Juil 2019
Modifié(e) : Guillaume le 5 Juil 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 commentaires
Guillaume
Guillaume le 5 Juil 2019
Turns out that filter is actually about 3 times slower than a loop (R2019a)
Jan
Jan le 8 Juil 2019
Modifié(e) : Jan le 8 Juil 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by