How to rewrite recursive funtion without for-loop

Hi, I am struggling with a recursive function that includes multiplication as well as a vector. Is there a way to speed up performance and rewrite the calculation (probably without using a for-loop):
a=1:20;
b=5;
c=3;
x=zeros(size(a,2),1);
for i=3:size(x,1)
x(i)=a(1,i)+b*x(i-1)+c*x(i-2);
end
Many thanks for any help.

1 Comment

I have another problem with a recursive function that is a drag on performance. The problem is a condition on the vector within the for-loop and that the values of the vector are added to x(i-1) before multiplying it. Here is a short example:
m=20;
n1=floor(rand(m,1).*10);
n2=floor(rand(m,1).*10);
n3=floor(rand(m,1).*10);
x=zeros(m,1);
starting_point=4;
for i=starting_point:size(x,1)
if n1(i)>0 && n2(i)>0 && n3(i)>0
x(i)=0.5*(n1(i)+n2(i)-n3(i)+x(i-1));
end
end
Again, any help is much appreciated!

Sign in to comment.

 Accepted Answer

a = 1:20;
b = 5;
c = 3;
a1 = a;
a1(1:2) = 0;
x = filter(1,[1,-b,-c],a1(:));

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 9 Sep 2016

Commented:

on 9 Sep 2016

Community Treasure Hunt

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

Start Hunting!