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

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!

댓글을 달려면 로그인하십시오.

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2016년 9월 9일
편집: Andrei Bobrov 2016년 9월 9일
a = 1:20;
b = 5;
c = 3;
a1 = a;
a1(1:2) = 0;
x = filter(1,[1,-b,-c],a1(:));

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2016년 9월 9일

댓글:

2016년 9월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by