Turn my (easy) for loop into a recursive function?

9 views (last 30 days)
Hi all. I'm really stuck on this problem - probably simple for many people here. I'm given a number as an input. As my output, I just want a row vector of those digits. The code I have below works FINE and gives the desired result: say my input is N = 65479 and I run baseDigits(N).
function D = baseDigits(N)
D = zeros(1,length(num2str(N)));
for i = 1:length(num2str(N))
if N>0
D(i) = rem(N,10);
N = floor(N/10);
D = D(end:-1:1);
This gives me D = [6 5 4 7 9] as expected. The problem is, I'm supposed to use a while loop and make it a recursive function to do the same thing. It's supposed to be less than 10 lines long and it's supposed to be an easy problem... I just don't think it's 'clicked' on how recursive functions store intermediate values. I have something like:
function D = baseDigits(N)
if N<10
D = N
while N>=10
N = floor(N/10)
D = [baseDigits(N),rem(N,10)]
I'm not sure how to properly append the values or how they're stored in the meantime. Any help is greatly appreciated. Thanks! :)

Accepted Answer

Alfonso Nieto-Castanon
Alfonso Nieto-Castanon on 15 Jul 2014
Edited: Alfonso Nieto-Castanon on 15 Jul 2014
You almost got it. Your are just: 1) overwriting the variable N, which you probably did not intend; and 2) including an unnecessary while loop, recursivity takes care of that:
function D = baseDigits(N)
if N<10
D = N;
M = floor(N/10);
D = [baseDigits(M),rem(N,10)];
EDIT: my guess is that the 'while loop' and the 'recursive function' are likely two separate requirements, because a recursive function for this problem that also includes a while loop seems awfully strange...
  1 Comment
Michael on 15 Jul 2014
1) Thanks so much for the fast response!
2) The only requirement was to do it as a recursive function. However, a while loop was given as a direct hint from one of the instructors but I'm not sure why. It really confused me in that context. Thanks again!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by