create a vector whose elements depend on its previous elements without a loop
Mostra commenti meno recenti
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
"As loops take considerable time..."
Loops do not take "considerable time". Badly written code inside a loop might be slow, or an algorithm might require slow code or many iterations, but loops in themselves are fast.
Have you read the documentation on how to write efficient MATLAB code?:
In particular, did you preallocate any output arrays before the loop?
Galgool
il 5 Lug 2019
Guillaume
il 5 Lug 2019
Yes, it can be done. Haven't you seen my answer?
Have you proven yet that the loop is a bottleneck? If not, why are you trying to optimise it? You're probably focusing on the wrong part of your code.
Note that while it can be done without a loop, testing on my computer shows that it is signficantly faster with a loop:
>> filter_vs_loop(1e6)
Comparing array creation of 1000000 elements, with a loop or filter
With loop: 0.00579613 s
With filter: 0.0146097 s
With loop: 0.00560415 s
With filter: 0.0146441 s
With loop: 0.00564641 s
With filter: 0.0145454 s
With loop: 0.00556884 s
With filter: 0.0147495 s
With loop: 0.00566302 s
With filter: 0.0146408 s
Galgool
il 7 Lug 2019
Guillaume
il 8 Lug 2019
filter can't be used for that and I doubt there's anything faster than a loop.
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.
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!