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

8 次查看(过去 30 天)
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 个评论
Jan
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.

请先登录,再进行评论。

采纳的回答

Guillaume
Guillaume 2019-7-5
编辑:Guillaume 2019-7-5
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 个评论
Jan
Jan 2019-7-8
编辑:Jan 2019-7-8
@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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by