create a vector whose elements depend on its previous elements without a loop
显示 更早的评论
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 个评论
"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
2019-7-5
Guillaume
2019-7-5
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
2019-7-7
Guillaume
2019-7-8
filter can't be used for that and I doubt there's anything faster than a loop.
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.
采纳的回答
更多回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!