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!