Getting rid of the for loop

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.

 Accepted Answer

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 Comments

Ok sorry I will include my full code. My function works fine I just want to eliminate all the for loops from the code to see how it would work. Perhaps if you could show me how to do it with one part I can try work it out for the others. The code works out repetition and non repetition is division problems.
function [a,b]=mytest(p,q)
for n=1
if (10^n)*p<q
n=n+1;
elseif (10^n)*p>q
break
end
end
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);
for j=1:(i-1)
if currentvalue(i)==currentvalue(j)
filler_a=quotient(1:(j-1));
b=quotient(j:(i-1));
a= [zeros(1,n-1),filler_a]
return
end
end
The recursive getrv function should allow you to replace the one for loop block that you presented in your question. Try using it and verify that it does what you expect.
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.
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?

Sign in to comment.

More Answers (0)

Categories

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

Asked:

Max
on 7 Nov 2015

Edited:

Max
on 10 Nov 2015

Community Treasure Hunt

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

Start Hunting!