필터 지우기
필터 지우기

Getting rid of the for loop

조회 수: 2 (최근 30일)
Max
Max 2015년 11월 7일
편집: Max 2015년 11월 10일
D
I'm having trouble getting rid of the for loop in my function. I have written out this code that works fine but I would like to get rid of the for loop and have it operate the same, i.e recursively. Thank you for the help in advance.

채택된 답변

Geoff Hayes
Geoff Hayes 2015년 11월 7일
Max - please include all of your code and describe what the above is intended to do. It appears to be some sort of factoring (?) algorithm.
A recursive function for the above for loop could be
function [r,v] = getrv(q,qn,r,v)
if qn<=q+1
if r>q
vn = floor(r/q);
rn = 10*(r-vn*q);
else
vn = 0;
rn = 10*r;
end
[rn,vn] = getrv(q,qn+1,rn,vn);
r = [r rn];
v = [v vn];
end
and it would be called from your main function as
[r,v] = getrv(q,2,10*p,0);
Note how the recursive call to getrv is concatenated with the r and v inputs.
  댓글 수: 4
Max
Max 2015년 11월 7일
Sorry, I heavily modified the for loop you initially wrote it for. Would you be able to show me for this isolated section
i=1;
currentvalue(i)=(10^n)*p;
for i=1:(q+1)
quotient(i) = floor(currentvalue(i)/q);
Remainder(i) = currentvalue(i)-(quotient(i)*q);
currentvalue(i+1) = 10*Remainder(i);
end
Sorry for the bother but I would really appreciate it. Thank you.
Geoff Hayes
Geoff Hayes 2015년 11월 7일
Max - use my example as a guide to modify the above code so that the for loop is replaced. Since you want to replace the above with a recursive function, ask yourself what should the inputs be to subsequent calls to the function? What should the output be? What is your stopping condition?

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by